How to get the dimensions of image with React?

Sometimes, we want to get the dimensions of image with React.

In this article, we’ll look at how to get the dimensions of image with React.

How to get the dimensions of image with React?

To get the dimensions of image with React, we can get it from the load event handler of the image.

For instance, we write:

import React from "react";

export default function App() {
  const onImgLoad = ({ target: img }) => {
    const { offsetHeight, offsetWidth } = img;
    console.log(offsetHeight, offsetWidth);
  };

  return (
    <div>
      <img
        onLoad={onImgLoad}
        alt=""
        src="https://i.picsum.photos/id/360/200/300.jpg?hmac=Fl1CgUfxrFjmcS1trYDG80XpEjYixcXfc2uTtCxFkDw"
      />
    </div>
  );
}

We define the onImgLoad function that gets the image from the target property.

Then we destructure the offsetHeight and offsetWidth properties from the image.

Next, we log the height and width with console.log.

Finally, we set the onLoad prop’s value to the onImgLoad function so onImgLoad is run when the image loads successfully.

Conclusion

To get the dimensions of image with React, we can get it from the load event handler of the image.