How to check for broken images in React JS How to check for broken images in React JS reactjs reactjs

How to check for broken images in React JS


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'}


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:

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

How I handled the error:

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


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:

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