Skip to content
Advertisement

react.js Replace img src onerror

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 error.

I would normally use the onerror method in the img tag but that doesn’t seem to be working.

I am not sure how to do this with react.

Here is my component:

JavaScript

Advertisement

Answer

Since there is no perfect answer, I am posting the snippet I use. I am using reusable Image component that falls back to fallbackSrc.

Since the fallback image could fail again and trigger infinite loop of re-rendering, I added errored state.

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement