Tag Archives: img

Fallback image if src doesn’t exist for image tag – ReactJS

Hey everyone,

I have a small list component that I wanted to populate with a custom image based on the entity’s id. Unfortunately, not all entities have an image so some were appearing broken.

In order to get around this I used the img tag’s onError attribute in ReactJS. If the image can’t be found it the callback is invoked. In the callback I set the src of the image tag to a known placeholder.

<img
   src={`/img/widgets/${widgetId}.jpg`}
   style={{
      height: 50,
      width: 50,
   }}
   onError={(e: any) => e.target.src = '/img/widgets/no-image.jpg'}
/>

Using this attribute allows me to use a known convention to automatically populate images and then fallback to a suitable default if it’s not available.

I found the following links pretty handy when looking for a solution: https://stackoverflow.com/a/64326984/522859