Answer the question
In order to leave comments, you need to log in
Why doesn't the onload event fire on img?
I wrote a simple component that takes two required props - src
and previewUrl
, where previewUrl
- is a lighter version of the image.
The task of the component is to display a light version of the image, and when the main one is loaded, then replace the y img
link. It would seem that the idea is simple and logical, but nothing works :) Namely, there is no GET
request for a picture, and accordingly it does not work, onload
and why I xs.
Help me to understand. Here is the codepen of the task https://codepen.io/fsdev/pen/bLWgoL
class Image extends React.Component{
static preloadImage(url){
return new Promise((resolve, reject) => {
const image = new Image();
image.onload = resolve;
image.onerror = reject;
image.src = url
})
}
constructor(){
super();
this.state = {
src: null
};
}
componentWillMount(){
const { src: bigImage, previewUrl } = this.props;
this.setState({src: previewUrl});
Image.preloadImage(bigImage)
.then(() => {
console.log("Loaded");
this.setState({src: bigImage})
})
.catch(e => console.error(e.message))
}
render(){
const { src } = this.state;
const { previewUrl, ...rest } = this.props; //eslint-disable-line
return(
<img {...rest} src={src} />
)
}
}
class App extends React.Component {
render(){
return(
<Image src="http://res.cloudinary.com/playhs/image/upload/v1518304840/bsyjqxahzr8bmaxuvj04.png"
previewUrl="http://res.cloudinary.com/playhs/image/upload/q_30/v1518304850/ztpj7gnqazk6ng2tzamk.jpg"
/>
)
}
}
ReactDOM.render(
<App/>, document.body
)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question