Building a Responsive Masonry Layout in React

Tamjid Mostafa

Tamjid Mostafa

ยท 2 min read
Building a Responsive Masonry

A Masonry layout is a popular design pattern used to display items of varying heights in a grid-like format. This layout is often used in image galleries, news portals, and e-commerce sites to create a visually appealing and flexible display of content. In this article, we will walk through the process of creating a responsive Masonry layout in React using functional components and hooks.

1. Understanding the Masonry Layout

The Masonry layout arranges items in a grid where items are positioned optimally with a minimal amount of vertical space between them. Unlike traditional grid layouts, Masonry doesn't require all rows to have the same height, making it ideal for displaying content with varying dimensions.

2. Creating the Masonry Component

We'll start by creating a Masonry component that will take children elements, divide them into columns, and display them in a flexible grid.

Masonry Component

import React from "react";
import PropTypes from "prop-types";

const Masonry = ({
children,
columnsCount = 3,
gutter = "0",

React.Children.forEach(children, (child) => {
if (child && React.isValidElement(child)) {
columns[validIndex % columnsCount].push(child);
validIndex++;
}
});
return columns;
};

// Helper function to render columns
const renderColumns = () => {
return getColumns().map((column, i) => (
<ItemTag
key={i}
style={{
display: "flex",
flexDirection: "column",
justifyContent: "flex-start",
alignContent: "stretch",
flex: 1,
width: 0,
gap: gutter,
...itemStyle,
}}
>
{column.map((item) => item)}
</ItemTag>
));
};

return (
<ContainerTag
style={{
display: "flex",
flexDirection: "row",
justifyContent: "center",
alignContent: "stretch",
boxSizing: "border-box",
width: "100%",
gap: gutter,
...style,
}}
className={className}
>
{renderColumns()}
</ContainerTag>
);
};

Masonry.propTypes = {
children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]).isRequired,
columnsCount: PropTypes.number,
gutter: PropTypes.string,
className: PropTypes.string,
style: PropTypes.object,
containerTag: PropTypes.string,
itemTag: PropTypes.string,
itemStyle: PropTypes.object,
};

export default Masonry;

Tamjid Mostafa

About Tamjid Mostafa

๐Ÿš€ Full-Stack Developer | Innovator | Creator
I'm a full-stack developer with 2+ years of experience, passionate about creating innovative web solutions. I specialize in building scalable applications using modern technologies and best practices.

๐ŸŽฅ Passionate About Sharing & Building
My expertise spans across the entire development stack, from designing intuitive user interfaces to implementing robust backend systems.๐ŸŒŸ

#coding, #youtube, #webdevelopment, #contentcreation, and #fullstackwebdeveloper,