How to handle broken images in React | fallback for broken images

This tutorial shows how to fix broken images in react application.

Let’s see How to create and display images?

Html provides img tag to display images

<img src="first.png" alt="Image example" />

The image displayed in a web browser, What if first.png is not found or gives a 404 error.

Html provides onerror for fallback images if the src image gives an error or 404

<img src="first.png" onerror="this.src='error.png';this.onerror='';" />

The same we can handle in react component.

How to handle broken images in React Component?

img tag used to display in react component. The below component displays an image with alt text.

import logo from "./logo.svg";
import "./App.css";

function App() {
  let logotext = "Hello World logo";
  return (
    <div className="App">
      <img src={logo} className="App-logo" alt={logotext} />
    </div>
  );
}

export default App;

So img tag in react contains onError attribute that can set an src attribute with new image. One way using inline function declaration

<img src="{logo}" className="App-logo" alt="{logotext}" onError="{e" ="" /> {
e.currentTarget.src = "error.png"; }} />

or you can write an event binding function

<img
  src="{logo}"
  className="App-logo"
  alt="{logotext}"
  onError="{this.getImageError}"
/>

And the binding function

getImageError = (e) => {
  e.currentTarget.src = "error.png";
};

Here is an complete code to handle image error in react component

import logo from "./logo1.svg";
import "./App.css";

function App() {
  let logotext = "Hello World logo";
  getImageError = (e) => {
    e.currentTarget.src = "error.png";
  };
  return (
    <div className="App">
      <img
        src={logo}
        className="App-logo"
        alt={logotext}
        onError={this.setImageError}
      />
    </div>
  );
}
export default App;