Joseph
Joseph

Reputation: 4725

TypeScript React <img /> onLoad event.target can't find naturalWidth naturalHeight

enter image description here

return <img {...props} onLoad={event => {
  console.log(event.target.naturalWidth)
}}/>

I want to retrieve naturalWidth & naturalHeight in TypeScript React.

But got stuck, TypeScript can't find that property.

How do I retrieve naturalWidth & naturalHeight in TypeScript React?

Upvotes: 5

Views: 4457

Answers (3)

mrwnt10
mrwnt10

Reputation: 1415

I had to use a type assertion:

const { width, height } = e.currentTarget as HTMLImageElement;

Upvotes: 2

mizkichan
mizkichan

Reputation: 619

You can access HTMLImageElement through event.currentTarget (not event.target) so this should work:

return <img {...props} onLoad={event => {
  console.log(event.currentTarget.naturalWidth)
}}/>

Upvotes: 5

priyadarshini puja
priyadarshini puja

Reputation: 139

You can try innerWidth and innerHeight.

console.log(event.target.innerWidth)

Upvotes: 0

Related Questions