{

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;
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

Basic React Interview questions and answers

Best ways to add an element to an array in React state with examples

Difference between Development and Production Builds in React

Difference between pureComponent and component in React

Difference between super and super props in React constructor class?

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

Getting started with ReactJS Bootstrap Tutorials with examples | reactstrap tutorials