{

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 not found or gives 404 error.

Html provides onerror for fallback images if 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;
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

ReactJS Append variables with strings, jsx state and prop concatenate html

How to display the content of a JSON file in React with example

Reactjs Fix Must call a super constructor in derived class before accessing this

How to change default port in React with create-react-app command?

How to create an react typescript application | Create-react-app typescript application

Fixing an error You are running create-react-app 4.0.3, which is behind the latest release (5.0.0) in React

How to fix Import In the body of module; reorder to top import/first? in React and javascript