Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

111
Views
Handle onError image on mapping React

I have this images iterating, and only on error of image I have to add a background color to the parent element div. So my code is like this

 
import React, { useState, useEffect } from 'react'
import COLORS from 'core/colors/colors'
...

export const ComponentSample: React.FC = () => {
 
 const [imagePlaceholder, setImagePlaceholder] = useState(false)
  const addDefaultSrc = (ev) => {
   
    if (!ev.currentTarget.onerror) {
      setImagePlaceholder(true)
    }
    ev.target.src = 'https://socialistmodernism.com/wp-content/uploads/2017/07/placeholder-image.png?w=640'
    ev.currentTarget.className = styles.placeholderImg;
  }
  console.log(imagePlaceholder)
  const colors = Object.values(COLORS)
  const randomColor = imagePlaceholder ? colors[Math.floor(Math.random() * colors.length)] : COLORS.white

 return <div className={styles.container}>
 <div className={styles.imageContainer} key={index} style={{ backgroundColor: randomColor }} >
                      <img src={project.thumbnailUrl} onError={addDefaultSrc} className={styles.imagePost} />
 
 </div>
 
 }

The problem here is that imagePlaceholder is becoming true and always returning true, I don't know how to make only on image that has error

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!