Replace the update status if the image is not found.

It seems I can not get around this problem. What I'm trying to do is attempt React to verify that the image does not return 404 to display an alternate image. Something like the one below does not work, since React does not wait for the image to try to load to return 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} />}; }, 

In the above code, the images will only display perfectly, but the 404 alternate image is not displayed.

I tried putting this in another method outside of getInitialState. I also tried to get it to call an external method outside of the React component, but nothing works.

There is a short method for adding the onerror attribute to the image tag itself, but it seems that React has the same problem as not executing this code and / or updating the result itself based on the result.

I think the most annoying part is that I don't have a function called so that React can work with a JavaScript image object.

Thanks for any help you can provide.

+6
source share
2 answers

It is a bad habit to put components in a state. You probably need something like the following:

 var Img = React.createClass({ componentDidMount: function () { var self = this; var img = new Image(); img.onerror = function () { self.setState({ src: 'http://i.imgur.com/lL3LtFD.jpg' }); }; img.src = this.state.src; }, getInitialState: function () { return { src: '/404.jpg' }; }, render: function () { return <img src={this.state.src} />; } }); 

jsfiddle link: http://jsfiddle.net/e2e00wgu

+14
source

Here is the solution I came across. Very new to Response and programming in general, so grab this with a piece of salt.

 const DEFAULT_IMAGE="http://i.imgur.com/lL3LtFD.jpg" <img src={this.props.SRC} onError={(e)=>{e.target.src=DEFAULT_IMG}}/> 

A WARNING. If the default constant is not valid, the browser will be caught in an infinite loop (at least when I checked it in Chrome). I have not found a solution for this yet, but in javascript with vanilla you set the onerror attribute to null, which tells the browser to make only one request for the asset.
jQuery / javascript to replace broken images

+12
source

Source: https://habr.com/ru/post/984394/


All Articles