I have a react component that is the detail view from a list.
I am trying to replace the image with a default image if the image does not exist and there is a 404 er
Ran into a similar problem and the best solution i could find was Georgii Oleinikov's answer. (Doesn't require making new imageLoadError state as suggested by Nitesh Ranjan in his answer)
onError={(e)=>{ if (e.target.src !== "image_path_here"){
e.target.onerror = null;
e.target.src="image_path_here";}
}
}
e.target.onerror = null is not needed (and doesn't really help) because the if condition is enough to prevent the infinite loop(if backup image fails to load as well).
So:
onError={(e)=>{ if (e.target.src !== "image_path_here"){
e.target.src="image_path_here";}
}
}
EDIT: The other way around is to set a flag outside the return brackets and check for the flag in the if statement. Code should look something like this:
render(){
let errorflag=true;
return(
{ if (errorflag){ errorflag=false; e.target.src=url; } }} />
);
}