Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React onLoad img event not working as expected

I'm writing a simple application that fetches a list of images as backgrounds (different sizes of the same image) and want to implement something like:

Small one loaded -> Set background, start fetching medium -> Medium loaded -> Set background, start fetching large

To accomplish this I'm setting a prefetch element, to load the image, and onLoad, set the background and start prefetching the next one.

According to this article it should be as simple as:

<img src={image} alt="" onLoad={console.log('LOADED')}/>

And I should see a LOADED message after the image is completely loaded by the client.

That's not happening.

Am I missing something?

Thanks in advance!

EDIT: The LOADED message appears when the component mounts.

like image 497
Mauricio Machado Avatar asked May 05 '18 22:05

Mauricio Machado


1 Answers

The problem

You're missing an arrow function expression. The direct call of the function will cause the console.log() to be fired as soon as the component is mounted. This is a common misconception, and is syntax related.

What happens

The function

onLoad={console.log('LOADED')} is called as soon as the component is mounted, since you're actually calling the console.log not just setting up which function should be called when the event is fired, in this case the onLoad.

How to fix it

What you want to do is introduce an arrow function in there, so that you're calling the function when the onLoad is actually called.

<img src={image} alt="" onLoad={() => console.log('LOADED')}/>

You might also want to pass down event properties from the event. You can do this by introducing a variable for the event:

<img onLoad={(event) => this.myHandleImageLoadEvent(event)} />

Where the function myHandleImageLoadEvent is a function defined in the same class and has the event as an input parameter.

like image 129
Thomas Darvik Avatar answered Oct 24 '22 03:10

Thomas Darvik