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