Skip to content Skip to sidebar Skip to footer

How To Check For Broken Images In React Js

I'm writing a module that takes article data from json and shows a large image over the article text, a hero module as they say. I've got the data and have set it up so if there is

Solution 1:

There is a native event for images called onerror that lets perform an action if the image cannot be loaded.

<img onError={this.addDefaultSrc} className="img-responsive" src={newsImage} alt={headline}/>

//in your componentaddDefaultSrc(ev){
  ev.target.src = 'some default image url'
}

Solution 2:

Here is what I did to check if the image is broken. There is an attribute called onError which is called when the image is broken or cannot be loaded. For example, here is the img tag:

<imgid={logo.id}src={logo.url}alt ={logo.name}onError={this.handleImageError} />

How I handled the error:

handleImageError = e => { //write your logic here.}

Solution 3:

In case that you know the image's error will be the absence of it like you are looping a gallery of profiles and some of them do not have pictures available, then you can simply insert the image's path as a callback like this:

<imgheight="auto"width={140}src={bizLogo || "/img/error.png"}
   alt="test"
/>

Solution 4:

As mentioned, onError is the way to go.

If you're looking for a component that handles this for you, try https://github.com/socialtables/react-image-fallback

Solution 5:

According to my understanding you want to see broken images. you should call a method in onError attribute. Check this jQuery/JavaScript to replace broken images

Post a Comment for "How To Check For Broken Images In React Js"