Mauricio Machado
Mauricio Machado

Reputation: 643

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.

Upvotes: 4

Views: 21453

Answers (1)

Thomas Darvik
Thomas Darvik

Reputation: 791

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.

Upvotes: 9

Related Questions