1

I am creating an img tag that i want to listen to the onLoad event for, but I also need the actual image object so i can check width/height, etc on it. These are created dynamically, so I can't know the id beforehand.

//In the JSX:
<img src={this.generateSrc(config)} onLoad={this.handleOnLoad} />

In normal javascript, I could do:

<img onload="someFunction(this)" />

How do I pass that in ReactJS?

2 Answers 2

2

You could get actual image object via e.target.

handleOnLoad(e) {
    console.log(e.target);
}

Or via Refs to Component

handleOnLoad() {
    console.log(this.refs.img);
}

<img ref='img' src={this.generateSrc(config)} onLoad={this.handleOnLoad.bind(this)} />
Sign up to request clarification or add additional context in comments.

4 Comments

Safari and Firefox don't pass an event to that callback
@DonRhummy, sorry I didn't test that. Or you could set a ref in img and retrieve it via this.refs.img
it creates hundreds of them dynamically, not just one
not true, safari and firefox both register the target of the onload event of an image
0

future javascript allows you to do:

handleOnLoad = (e) => {
  console.log(e.target);
}

<img src={imgSrc} onLoad={this.handleOnLoad} />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.