How to handle errors on HTML `img` tag in React

How to handle errors on HTML `img` tag in React

Play this article

Today I'm going to talk about how to handle image-loading error with ReactJS and TypeScript

The motivation to write this is When I work on the NextJS application in my office, our UI designer provides me with two image types, for default loading a webp file and for fallback jpeg file, This is the first time I'm adding a fallback image to a img tag :( my bad

So I search for how to do this using React and Typescript,

I found this answer in StackOverflow

  onError={({ currentTarget }) => {
    currentTarget.onerror = null; // prevents looping
    currentTarget.src = "image_path_here";

Then I tried to make this more TS-compatible version

And this is it


const onErrorImage = ({ currentTarget }: SyntheticEvent<HTMLImageElement, Event>): void => {
  currentTarget.onerror = null;
  currentTarget.src = imageFallbackURL;


  return (
        alt="your alt here"

But we have picture tag now so We can improve this as following

  <source srcSet={avifSrc} type={"image/avif"} />
  <source srcSet={webpSrc} type={"image/webp"} />