DEV Community

Cover image for Handling Broken Images in React
Lev Eidelman Nagar
Lev Eidelman Nagar

Posted on

Handling Broken Images in React

Often when linking to an external resource we run the risk of that resource being unavailable. In the case of an image we will get the dreaded broken image icon:

Image description

Lucky for us as web developers, the <img> tag accepts an onerror event which we can use to handle a missing or otherwise broken image.

This is how we can leverage this in React with Typescript:

import { HTMLProps, ReactNode, useState } from "react"

/**
 * We extend `<img>`'s properties as we want our 
 * component to act as a drop-in replacement for it
 */
type ImgProps = HTMLProps<HTMLImageElement> & {
   /**
   * Optional fallback to render in place of a missing image
   * @default null
   */
  fallback?:  ReactNode
}

export function Img(props: ImgProps) {
  const { fallback = null } = props;

  /**
   * is our image broken?
   */
  const [isBroken, setIsBroken] = useState(false);

  function handleError() {
    setIsBroken(true)
  }

  if (isBroken) {
    return fallback;
  }

  return <img onError={handleError} {...props} />
}
Enter fullscreen mode Exit fullscreen mode

Now, it is simply a matter of replacing the default <img> tag with our custom <Img> component:

import { Img } from './Img'

function App() {

  return (
    <>
      {/* Regular old image */}
      <img src='https://nosuchsite/nosuchimage.png' />

      <hr/>

      {/* Our custom image component */}
      <Img src='https://nosuchsite/nosuchimage.png' fallback={<div>🚧 image not found 🚧</div>} />
    </>
  )
}

export default App

Enter fullscreen mode Exit fullscreen mode

Which will result in:

Image description


I hope you found this post to be helpful!

Top comments (0)