Taghi Khavari
Taghi Khavari

Reputation: 6582

Is there a way in react to find out if an image resource fails to load?

I have a list of images that I'm looping through and will show them in my components but I have a problem, consider some of these images won't load due to server failure, so my question is how can I provide a fallback for these images.

for example:

imageResourses.map(src => src ? <img src={src} /> : <FallbackImageComponent />)

My challenge is if an src property exists I show the actual image which can lead to a none desire output due to server failure.

So how can I show My FallbackImageComponent in case there was a problem with loading the image?

Upvotes: 1

Views: 783

Answers (1)

Yash Joshi
Yash Joshi

Reputation: 2784

You can create a reusable Image Component which will render a fallback image whenever the image is not resolved.

Here is the sample code for Image component:

class Image extends React.Component {
  state = {
    hasError: false
  };

  handleError = (e) => {
    this.setState({
      hasError: true
    });
  };

  render() {
    if (this.state.hasError) {
      return "Error Fallback Image";
    }

    return <img {...this.props} onError={this.handleError} />;
  }
}

Usage:

<Image src="..." />

See the working here: https://codesandbox.io/s/heuristic-snow-5295o?file=/src/App.js:348-660

Note: There may be other solutions as well. If I stumble upon them I will update the answer.

Upvotes: 2

Related Questions