Skip to main content

Masonry

The Masonry layout is a useful technique that enables you to create a grid of images with varying widths and heights. Masonry comes with two fill-mode options to change the way the images are displayed.

There are two fill modes: VERTICAL and HORIZONTAL. When using VERTICAL fill mode, the images are placed from top to bottom. Once the boundary is reached, the next image will be rendered from the next column. Similarly, in the HORIZONTAL fill mode, the images are filled row by row, and once the boundary is reached, the next image will be placed from the next row.

To use the Masonry component, you must pass images as children and wrap them in either a span or div element. You should specify the width and height of the image as a class, naming your class using the format rc-w-width and rc-h-height.

Let's create a simple masonry grid with ten items to illustrate how to use the component. In this example, we will try to fill the images row by row.

Masonry-Horizontal.jsx
import { Masonry } from "react-visual-grid";

<Masonry fillMode="HORIZONTAL" height={1200} width={300}>
<span className={`rc-w-100 rc-h-100`}>
<img alt="Image 1" src={`https://picsum.photos/id/10/100/100`} />
</span>
<span className={`rc-w-200 rc-h-100`}>
<img alt="Image 2" src={`https://picsum.photos/id/11/100/100`} />
</span>
<span className={`rc-w-200 rc-h-100`}>
<img alt="Image 3" src={`https://picsum.photos/id/13/200/100`} />
</span>
<span className={`rc-w-100 rc-h-100`}>
<img alt="Image 4" src={`https://picsum.photos/id/14/100/100`} />
</span>
<span className={`rc-w-300 rc-h-150`}>
<img alt="Image 5" src={`https://picsum.photos/id/15/200/100`} />
</span>
</Masonry>

The visual representation of how the masonry will look is shown below.

horizontal_masonry

To fill the images vertically instead of horizontally, we can use the same images as above but with the VERTICAL fill mode.

Masonry-Vertical.jsx
import { Masonry } from "react-visual-grid";

<Masonry fillMode="VERTICAL" height={300} width={600}>
<span className={`rc-w-100 rc-h-100`}>
<img alt="Image 1" src={`https://picsum.photos/id/10/100/100`} />
</span>
<span className={`rc-w-100 rc-h-200`}>
<img alt="Image 2" src={`https://picsum.photos/id/11/100/100`} />
</span>
<span className={`rc-w-200 rc-h-300`}>
<img alt="Image 3" src={`https://picsum.photos/id/13/200/100`} />
</span>
<span className={`rc-w-150 rc-h-100`}>
<img alt="Image 4" src={`https://picsum.photos/id/14/100/100`} />
</span>
<span className={`rc-w-150 rc-h-200`}>
<img alt="Image 5" src={`https://picsum.photos/id/15/200/100`} />
</span>
</Masonry>

Here is the visual representation of how the masonry will look like for the above code.

vertical_masonry

use the gap property to add spacing between the images.

CodeSandBox