Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

117
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda