DEV Community

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

Posted on

11

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!

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more