Skip to main content

Masonry

We want to create a gallery of images in a column format. One way we can achieve this is using the <Grid/> component.

How does it work?

We create a <Grid/> with the desired number of rows and columns, then place img items in individual cells.

info

The images below were taken from Lorem Picsum. It's an awesome site.

The demo

The code

tip

Our example here is relatively uniform. All the rows have the same height and all the columns have the same width. We can get more variation by providing different rows heights, via the rowHeights property on the grid. We can similarly use the columnWidths prop to create columns of different width.

import { Grid } from "@resembli/react-virtualized-window"

const heights = [200, 300, 150, 100]

export function VirtualizedMasonry() {
const imgUrls = Array.from({ length: 100 }, () =>
Array.from({ length: 5 }, () => {
const randomInt = Math.floor(Math.random() * 100)
return `https://picsum.photos/250/${heights[randomInt % 4]}`
}),
)

return (
<div style={{ height: 500 }}>
<Grid data={imgUrls} defaultColumnWidth="20%" defaultRowHeight={200}>
{({ data: url, style }) => {
return (
<div
style={{
padding: 10,
...style,
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
>
<img src={url} alt="Random image from picsum" />
</div>
)
}}
</Grid>
</div>
)
}