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

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

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

<img
  src={record.picture}
  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 (
    <>
    ...
      <img
        alt="your alt here"
        onError={onErrorImage}
        src={imageDefaultURL}
      />
    ...
    </>
  );

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

<picture>
  <source srcSet={avifSrc} type={"image/avif"} />
  <source srcSet={webpSrc} type={"image/webp"} />
  <img
    alt={alt}
    height={height}
    loading={loading}
    src={fallback}
    width={width}
  />
</picture>