Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React update state if image not found.

Tags:

reactjs

I can't seem to wrap my head around this problem. What I'm trying to do is have React attempt to verify an image is not returning a 404 to display an alternative image instead. Something like the below does not work as React does not wait for the image to attempt to load for returning the component.

getInitialState: function () {
        var img = new Image();
        img.onerror = function() {
            img.src = "alternativeImage.jpg"
        },
        img.src = this.props.image;
        return {image: <img src={img.src} />};
    },

The above code will display the images just fine but the 404 alternative image does not show up.

I've tried to place this in another method outside of getInitialState. I've also tried to have it call an external method outside of the React component, but nothing works.

There is a short hand method of adding onerror attribute on the image tag itself, but it seems React has the same issue of not executing that code and or updating itself based on the outcome.

I think the most frustrating part is that I cannot seem to have any function called that React would be able to work with from the JavaScript image object.

Thanks for any help you can provide.

like image 906
Chris Hawkes Avatar asked Mar 29 '15 17:03

Chris Hawkes


1 Answers

Here's a solution that I came up with. Pretty new to React and programming in general so take this with a grain of salt....

const DEFAULT_IMAGE="http://i.imgur.com/lL3LtFD.jpg"

<img src={this.props.SRC} onError={(e)=>{e.target.src=DEFAULT_IMG}}/>

WARNING: If the default constant is invalid, the browser will be caught in an infinite loop (at least when I tested this in Chrome). I haven't found a solution to this yet, but in vanilla javascript, you set the onerror attribute to null which tells the browser to make only a single request for the asset.
jQuery/JavaScript to replace broken images

like image 59
Adam Stein Avatar answered Dec 02 '22 02:12

Adam Stein