React is a popular JavaScript library for building user interfaces, especially for single-page applications. It allows developers to create reusable UI components. Masonry, on the other hand, is a grid layout based on columns. Unlike other grid layouts, it doesn't have fixed-height rows. This means it optimizes the use of space inside the web page by reducing any unnecessary gaps. When you combine these two, you get the React Masonry component.
Masonry layout is a popular web design technique used to display content of varying height in a grid-based UI. It is named after the masonry trade due to its resemblance to how bricks are stacked in a wall. The masonry layout is also known as the Pinterest Style Layout, as it was first used by Pinterest. In a masonry layout, each grid item is placed sequentially from top to bottom and left to right, fitting into the next open spot in the grid.
React Masonry Component is a powerful tool that allows developers to implement a masonry layout in their React applications. It provides a responsive, flexible grid layout that can accommodate elements of varying sizes. This component is particularly useful when you need to display a large number of elements in a limited space, such as image galleries or product listings.
1import React from 'react'; 2import Masonry from 'react-masonry-component'; 3 4const masonryOptions = { 5 transitionDuration: 0 6}; 7 8const imagesLoadedOptions = { background: '.my-bg-image-el' } 9 10function App() { 11 return ( 12 <Masonry 13 className={'my-gallery-class'} // default '' 14 elementType={'ul'} // default 'div' 15 options={masonryOptions} // default {} 16 disableImagesLoaded={false} // default false 17 updateOnEachImageLoad={false} // default false and works only if disableImagesLoaded is false 18 imagesLoadedOptions={imagesLoadedOptions} // default {} 19 > 20 <li className="image-element-class"> 21 <div> 22 <img src="path/to/image" /> 23 </div> 24 </li> 25 // more elements 26 </Masonry> 27 ); 28} 29 30export default App; 31
In the above example, we import the Masonry component from the react-masonry-component library and use it in our App function. The Masonry component takes several props, including className, elementType, options, disableImagesLoaded, updateOnEachImageLoad, and imagesLoadedOptions.
To create a simple masonry layout in React, we first need to install the react-masonry-component library. Navigate to your project directory and run the following command:
1npm install react-masonry-component 2
After the installation is complete, you can import the Masonry component into your JS file and use it to create a masonry layout. Here's a basic example:
1import React from 'react'; 2import Masonry from 'react-masonry-component'; 3 4function App() { 5 const childElements = [1, 2, 3, 4, 5].map((element) => 6 <div key={element}> 7 <h4>{element}</h4> 8 </div> 9 ); 10 11 return ( 12 <Masonry> 13 {childElements} 14 </Masonry> 15 ); 16} 17 18export default App; 19
In this example, we create an array of div elements and render them inside the Masonry component. The Masonry component will arrange these elements in a masonry layout.
To import masonry into your React applications, you need to install the react-masonry-component library. You can do this by running the following command in your terminal:
1npm install react-masonry-component 2
Once the library is installed, you can import it into your JS file like this:
1import Masonry from 'react-masonry-component'; 2
You can now use the Masonry component to create masonry layouts in your React app.
The react responsive masonry package allows you to create responsive masonry layouts that adjust according to different screen sizes. This package provides a ResponsiveMasonry component that takes two props: columns and breakpoints. The columns prop specifies the number of columns in the grid, and the breakpoints prop allows you to specify the number of columns at different screen widths.
Here's an example of how to use the ResponsiveMasonry component:
1import React from 'react'; 2import { ResponsiveMasonry } from 'react-responsive-masonry'; 3 4function App() { 5 return ( 6 <ResponsiveMasonry 7 columns={{ 320: 1, 480: 2, 800: 3 }} 8 breakpoints={{ 350: 2, 750: 3, 900: 4 }} 9 > 10 <div>Item 1</div> 11 <div>Item 2</div> 12 <div>Item 3</div> 13 // more items 14 </ResponsiveMasonry> 15 ); 16} 17 18export default App; 19
In this example, the grid will have one column for screens narrower than 480px, two columns for screens between 480px and 800px, and three columns for screens wider than 800px. The breakpoints prop allows you to adjust the number of columns at specific screen widths.
Infinite scroll is a popular feature in modern web design where content loads continuously as the user scrolls down the page, eliminating the need for pagination. This feature can be combined with masonry layouts to create a seamless browsing experience. Here's how you can implement infinite scroll in a masonry layout:
1import React, { useState, useEffect } from 'react'; 2import Masonry from 'react-masonry-component'; 3import InfiniteScroll from 'react-infinite-scroll-component'; 4 5function App() { 6 const [items, setItems] = useState(Array.from({ length: 20 })); 7 8 const fetchMoreData = () => { 9 setTimeout(() => { 10 setItems(items.concat(Array.from({ length: 20 }))); 11 }, 1500); 12 }; 13 14 return ( 15 <InfiniteScroll 16 dataLength={items.length} 17 next={fetchMoreData} 18 hasMore={true} 19 loader={<h4>Loading...</h4>} 20 > 21 <Masonry> 22 {items.map((item, index) => ( 23 <div key={index}> 24 Item {index} 25 </div> 26 ))} 27 </Masonry> 28 </InfiniteScroll> 29 ); 30} 31 32export default App; 33
In this example, we use the useState hook to manage the state of our items array. The fetchMoreData function is called when the user scrolls to the bottom of the page, adding more items to the array. The InfiniteScroll component wraps around the Masonry component, enabling the infinite scroll feature.
One of the advantages of using masonry layouts is the ability to customize the number of columns and the gaps between items. The Masonry component allows you to specify these values through its props. Here's an example:
1import React from 'react'; 2import Masonry from 'react-masonry-component'; 3 4function App() { 5 const childElements = [1, 2, 3, 4, 5].map((element) => 6 <div key={element}> 7 <h4>{element}</h4> 8 </div> 9 ); 10 11 return ( 12 <Masonry 13 columnWidth={200} 14 gutter={10} 15 > 16 {childElements} 17 </Masonry> 18 ); 19} 20 21export default App; 22
In this example, we set the columnWidth prop to 200 pixels and the gutter prop to 10 pixels. The Masonry component will arrange the child elements into columns of 200 pixels wide with a 10-pixel gap between each item.
Masonry layouts can be styled with CSS to match the look and feel of your website. You can apply styles to the Masonry component itself or to the individual items within the layout. Here's an example:
1import React from 'react'; 2import Masonry from 'react-masonry-component'; 3import './App.css'; 4 5function App() { 6 const childElements = [1, 2, 3, 4, 5].map((element) => 7 <div className="item" key={element}> 8 <h4>{element}</h4> 9 </div> 10 ); 11 12 return ( 13 <Masonry 14 className="my-masonry-grid" 15 columnClassName="my-masonry-grid_column" 16 > 17 {childElements} 18 </Masonry> 19 ); 20} 21 22export default App; 23
In this example, we apply the "my-masonry-grid" class to the Masonry component and the "my-masonry-grid_column" class to each column in the grid. We can then define these classes in our CSS file to style the layout.
The React Masonry Component offers several advanced features that can enhance the functionality and user experience of your masonry layouts. One such feature is the ability to animate the reordering of items within the layout. This can be achieved by setting the transitionDuration prop to a non-zero value.
Another feature is the ability to handle images within the layout. By setting the disableImagesLoaded prop to false, the Masonry component will wait for all images to load before rendering the layout. This ensures that the layout is correctly calculated even when it contains images of unknown size.
1import React from 'react'; 2import Masonry from 'react-masonry-component'; 3 4function App() { 5 const childElements = [1, 2, 3, 4, 5].map((element) => 6 <div key={element}> 7 <img src={`path/to/image${element}.jpg`} alt="" /> 8 </div> 9 ); 10 11 return ( 12 <Masonry 13 transitionDuration={500} 14 disableImagesLoaded={false} 15 > 16 {childElements} 17 </Masonry> 18 ); 19} 20 21export default App; 22
In this example, the Masonry component will animate the reordering of items with a duration of 500 milliseconds. It will also wait for all images to load before rendering the layout.
While working with React Masonry, you may encounter some common issues. One of these is the layout not rendering correctly when the size of the items changes dynamically. This can be fixed by calling the layout method on the Masonry instance whenever the size of the items changes.
Another common issue is the layout not updating when new items are added. This can be fixed by calling the addItems method on the Masonry instance with the new items as an argument.
1import React, { useRef, useEffect } from 'react'; 2import Masonry from 'react-masonry-component'; 3 4function App() { 5 const masonryRef = useRef(null); 6 const [items, setItems] = useState([1, 2, 3, 4, 5]); 7 8 useEffect(() => { 9 if (masonryRef.current) { 10 masonryRef.current.layout(); 11 } 12 }, [items]); 13 14 const addNewItem = () => { 15 setItems([...items, items.length + 1]); 16 if (masonryRef.current) { 17 masonryRef.current.addItems([items.length + 1]); 18 } 19 }; 20 21 return ( 22 <div> 23 <button onClick={addNewItem}>Add New Item</button> 24 <Masonry ref={masonryRef}> 25 {items.map((item) => 26 <div key={item}> 27 <h4>{item}</h4> 28 </div> 29 )} 30 </Masonry> 31 </div> 32 ); 33} 34 35export default App; 36
In this example, we use the useRef hook to create a reference to the Masonry instance. We then use the useEffect hook to call the layout method whenever the items state changes. The addNewItem function adds a new item to the items state and calls the addItems method on the Masonry instance.
In conclusion, the React Masonry Component is a powerful tool for creating responsive, flexible masonry layouts in your React applications. It offers a wide range of features and customization options, making it suitable for a variety of use cases. Whether you're building an image gallery, a product listing, or a blog post layout, React Masonry can help you create a visually appealing, space-efficient layout that enhances the user experience.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.