Dynamically get image dimensions from image URL in React

Prashant Shahi
1 min readJan 13, 2021

--

There might be cases when you would be required to obtain metadata of a media before it is loaded.

The usual way you would go about it is to have an API that gives back the media metadata from the server. But here we will be getting the image dimension using React.

Firstly, we will be creating an instance of the HTML Image element and then pass the image URL.

const img = new Image();img.src = imageUrl;

Next, we can access the image dimension using the #Image.onload function which will get called when the image is loaded.

img.onload = () => {
console.log(img.height);
console.log(img.width);
};

Now, we can enclose the code above in a function and pass back the dimension using React State hooks.

Introducing the states in the caller function/class:

const [imageDimensions, setImageDimensions] = useState({});

Inside the called function, we can set image dimensions using setImageDimensions to pass them back to the caller.

const setImageSize = (setImageDimensions, imageUrl) => {
const img = new Image();
img.src = imageUrl;
img.onload = () => {
setImageDimensions({
height: img.height,
width: img.width
});
};
};

Lastly, you may need to use useEffect to run the function once after the rendering.

You can find the complete code here:

--

--