Categories
React

Add a Masonry Grid to a React App with the react-masonry-css Library

Spread the love

We can add the masonry grid to a React app with the react-masonry-css library.

In this article, we’ll look at how to use the library to add the masonry grid.

Installation

We can install the package by running:

npm install react-masonry-css

Adding the Grid

After installing the package, we add the styles by writing:

styles.css

.my-masonry-grid {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  margin-left: -30px;
  width: auto;
}
.my-masonry-grid_column {
  padding-left: 30px;
  background-clip: padding-box;
}

.my-masonry-grid_column > div {
  background: yellow;
  margin-bottom: 30px;
}

to add the background color and make the items display with a flexbox layout.

Then we can use it by writing:

App.js

import React from "react";
import Masonry from "react-masonry-css";
import "./styles.css";

let items = [
  { id: 1, name: "one" },
  { id: 2, name: "two" },
  { id: 3, name: "three" },
  { id: 4, name: "four" },
  { id: 5, name: "five" }
];

items = items.map(function (item) {
  return <div key={item.id}>{item.name}</div>;
});

const breakpointColumnsObj = {
  default: 4,
  1100: 3,
  700: 2,
  500: 1
};

export default function App() {
  return (
    <div className="App">
      <Masonry
        breakpointCols={breakpointColumnsObj}
        className="my-masonry-grid"
        columnClassName="my-masonry-grid_column"
      >
        {items}
      </Masonry>
    </div>
  );
}

We add the breakpointColumnsObj to set the number of items to display when our screen meets the given width.

The keys are the screen sizes and the values are the number of items to display in a row.

className has the class name for the items.

columnClassName has the class name for the grid columns.

We render the items inside the Masonry component.

The class names must match what we have in the CSS file.

The grid is responsive, so the masonry grid will always fit on the screen.

Conclusion

We can add a masonry grid to a React app easily with the react-masonry-css library.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *