Efe FRK
Efe FRK

Reputation: 197

Why does it return undefined when I try to get the height and width of an image in react.js

I'm trying to log the height and the width values of an image to the console in react.js but they are (for some reason) undefined. Do you know why it is?

Here's the code:

export default function FilmPage(props) {
    const getImgSize = (img) => {
        let imageEl = <img onLoad={()=>{
            console.log(imageEl.width)
            console.log(imageEl.height)
        }} src={img} />

        return imageEl
    }
    
    return (
        <div className="proper-film">
            <div className="body">
                <div>{getImgSize(props.data.image)}</div>
            </div>
        </div>
    )

}

And also the data I retrieve looks like this:

data = {
    some: null,
    other: null,
    stuff: null,  
    image: "https://my_api.com/images/original/picture.jpg",
    and_more: null
}

By the way, when I tried debugging, there was no problem with the data I retrieve.

What would you recommend?

Upvotes: 0

Views: 552

Answers (1)

John Lobo
John Lobo

Reputation: 15319

You can modify getImgSize method like below

const getImgSize = (img) => {
    return <img onLoad={(e) => {
      console.log(e.target.offsetHeight)
      console.log(e.target.offsetWidth)
    }} src={img} />


  }

https://codesandbox.io/s/xenodochial-borg-x474m?file=/src/App.js

Upvotes: 1

Related Questions