S
S
Shaks2018-02-11 19:01:40
JavaScript
Shaks, 2018-02-11 19:01:40

Why doesn't the onload event fire on img?

I wrote a simple component that takes two required props - srcand 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 imglink. It would seem that the idea is simple and logical, but nothing works :) Namely, there is no GETrequest for a picture, and accordingly it does not work, onloadand 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

1 answer(s)
K
kn1ght_t, 2018-02-11
@shaks

return new Promise((resolve, reject) => {
            const image = document.createElement('img');
            image.onload = resolve;
            image.onerror = reject;
            image.src = url;
        });

this is how it works =)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question