Reputation: 6019
I'm trying to create an image gallery with a Masonry-like layout. It means the layout contains a few columns and with the same width and amount of columns depends on the current viewport width. The height of every item is flexible and depends on the Image that will be rendered in the particular gallery item. So the item wrapper doesn't have any limits for height but the width is limited
Previously I used the simple img
tag for every gallery item to render the image
<img src={src} alt={description} />
and it renders itself with the Width and Height the same as the original image has and it's exactly what I want because it renders itself with the various height and thus masonry layout works as it should.
So far so good but I'd like to use the Next.js Image component because it has a lot of nice features like lazy loading, loading blur placeholder, etc. however I can't figure out how to achieve the same behavior as in the standard img
use case.
I can't use the layout="fill"
with the width & height = 100%
because the parent container of the item doesn't have any height
<Image
width="100%" height="100%"
layout="fill"
src={src}
alt="Picture of the item"
/>
The image itself must be a "height-dictator" for the parent container and also I can't use the direct with/height values to set into the Image component because these properties are unknown for each image
So I'm wondering if it is possible at all to achieve this behavior in the case of Next.js Image component?
I'll appreciate any help & info!
Upvotes: 3
Views: 2319
Reputation: 149
Width and height in next/image Component should be integers without units. And they are pixels. layout="fill" is a different story. The width and height property could be calculated using JS if this is the only possibility you have.
Here are some cool ways to deal with that: How to get image size (height & width) using JavaScript?
All you have to do is run the calculation before attaching the image to the Image component.
what you are looking for is naturalWidth and naturalHeight of the image.
Upvotes: 2