@sebkolind/use-image-dimensions
v1.0.2
Published
A React Hook that loads image dimensions from a url
Downloads
3
Readme
use-image-dimensions
A React Hook that loads image dimensions from any URL. Supports @2, @3, @4, @x
images out of the box.
Installation
npm install @sebkolind/use-image-dimensions
Use Case
This hook is useful if you need to know the dimensions of an image before it is loaded. This can be useful for layout calculations or for preloading images. It will help you avoid layout shifts when the image is loaded.
Some time ago I built a hook that would read the width and height of an image before it was rendered in the DOM.
The reasoning behind this was to avoid layout shifts when my component was rendered. It's been sitting on GitHub without getting any attention at all, so I thought I'd share it with you!
The hook is called useImageDimensions
and it's available on npm. It's super easy to use and it supports @2, @3, @4, @x
images out of the box. Check it out here https://github.com/sebkolind/use-image-dimensions.
I hope you find it useful! 🚀
Usage
import {useImageDimensions} from '@sebkolind/use-image-dimensions'
const url = '[email protected]'
const Component = () => {
/**
* If the image URL contains a zoom multiplier (@2, @3, @4),
* the dimensions will be calculated by dividing width/height with the multiplier.
*/
const {width, height} = useImageDimensions(url,
{
/**
* Optional
*
* If you are concerned with UI flickering this could be helpful.
* Potential zoom multiplier will not be taken into consideration here,
* as this is a manual override of the hooks functionality.
*/
initialDimensions: {
width: 300,
height: 120,
}
}
)
return (
<img src={url} width={width} height={height} />
)
}