Convert Figma logo to code with AI

eiriklv logoreact-masonry-component

A React.js component for using @desandro's Masonry

1,446
145
1,446
61

Top Related Projects

16,466

:love_hotel: Cascading grid layout plugin

A blazing fast masonry layout generator for fixed width elements.

11,081

:revolving_hearts: Filter & sort magical layouts

Browser API's turned into declarative React components and HoC's

Animated grid layout component for React

Quick Overview

React-masonry-component is a React wrapper for the popular Masonry layout library. It allows developers to easily create responsive grid layouts with a cascading effect, commonly used for image galleries, Pinterest-style layouts, or any content that benefits from a dynamic grid arrangement.

Pros

  • Seamless integration with React applications
  • Supports server-side rendering (SSR)
  • Maintains the full feature set of the original Masonry library
  • Easy to use with a simple API

Cons

  • Depends on the Masonry library, which may increase bundle size
  • Limited customization options compared to building a masonry layout from scratch
  • May have performance issues with a large number of items
  • Documentation could be more comprehensive

Code Examples

  1. Basic usage:
import Masonry from 'react-masonry-component';

const Gallery = () => (
  <Masonry>
    <div className="item">...</div>
    <div className="item">...</div>
    <div className="item">...</div>
  </Masonry>
);
  1. With options:
import Masonry from 'react-masonry-component';

const masonryOptions = {
  transitionDuration: 0,
  itemSelector: '.item',
  columnWidth: 200,
};

const Gallery = () => (
  <Masonry
    className={'my-gallery-class'}
    elementType={'ul'}
    options={masonryOptions}
    disableImagesLoaded={false}
    updateOnEachImageLoad={false}
  >
    <li className="item">...</li>
    <li className="item">...</li>
    <li className="item">...</li>
  </Masonry>
);
  1. Handling layout updates:
import React, { useRef } from 'react';
import Masonry from 'react-masonry-component';

const Gallery = () => {
  const masonryRef = useRef(null);

  const handleLayoutComplete = (laidOutItems) => {
    console.log('Layout complete', laidOutItems);
  };

  const forceUpdate = () => {
    masonryRef.current.masonry.layout();
  };

  return (
    <Masonry
      ref={masonryRef}
      onLayoutComplete={handleLayoutComplete}
    >
      {/* Masonry items */}
    </Masonry>
  );
};

Getting Started

  1. Install the package:

    npm install react-masonry-component
    
  2. Import and use in your React component:

    import React from 'react';
    import Masonry from 'react-masonry-component';
    
    const MyGallery = () => (
      <Masonry>
        <div className="item">Item 1</div>
        <div className="item">Item 2</div>
        <div className="item">Item 3</div>
      </Masonry>
    );
    
    export default MyGallery;
    
  3. Add necessary CSS for your items:

    .item {
      width: 200px;
      margin-bottom: 10px;
    }
    

Competitor Comparisons

16,466

:love_hotel: Cascading grid layout plugin

Pros of Masonry

  • More versatile and can be used with various JavaScript frameworks or vanilla JS
  • Offers more layout options and customization features
  • Has a larger community and more extensive documentation

Cons of Masonry

  • Requires more setup and configuration for React projects
  • May have a steeper learning curve for React developers
  • Doesn't provide React-specific optimizations out of the box

Code Comparison

Masonry (vanilla JavaScript):

var msnry = new Masonry('.grid', {
  itemSelector: '.grid-item',
  columnWidth: 200
});

React Masonry Component:

import Masonry from 'react-masonry-component';

<Masonry
  className={'my-gallery-class'}
  elementType={'ul'}
  options={masonryOptions}
  disableImagesLoaded={false}
  updateOnEachImageLoad={false}
>
  {childElements}
</Masonry>

Summary

Masonry is a more flexible and feature-rich option suitable for various project types, while React Masonry Component provides a simpler, React-specific implementation. The choice between the two depends on the project requirements, developer expertise, and desired level of customization.

A blazing fast masonry layout generator for fixed width elements.

Pros of bricks.js

  • Lightweight and dependency-free, making it more versatile for various projects
  • Supports both horizontal and vertical layouts, offering more flexibility
  • Provides a simple API for easy integration and customization

Cons of bricks.js

  • Not specifically designed for React, requiring additional setup for React projects
  • Lacks some React-specific optimizations and integrations
  • May require more manual handling of state and updates in a React environment

Code Comparison

react-masonry-component:

import Masonry from 'react-masonry-component';

<Masonry
  elementType={'ul'}
  options={masonryOptions}
  disableImagesLoaded={false}
  updateOnEachImageLoad={false}
>
  {childElements}
</Masonry>

bricks.js:

import Bricks from 'bricks.js';

const instance = Bricks({
  container: '.container',
  packed: 'data-packed',
  sizes: [
    { columns: 2, gutter: 10 },
    { mq: '768px', columns: 3, gutter: 25 },
    { mq: '1024px', columns: 4, gutter: 50 }
  ]
});

instance.pack();

Both libraries offer efficient ways to create masonry layouts, but react-masonry-component is tailored for React applications, while bricks.js provides a more general-purpose solution that can be adapted to various frameworks or vanilla JavaScript projects.

11,081

:revolving_hearts: Filter & sort magical layouts

Pros of Isotope

  • More feature-rich, offering filtering, sorting, and animations in addition to masonry layout
  • Supports multiple layout modes beyond just masonry (e.g., fitRows, vertical)
  • Wider browser compatibility, including older versions

Cons of Isotope

  • Requires a commercial license for commercial use
  • Larger file size due to additional features
  • Not specifically designed for React, may require additional setup

Code Comparison

react-masonry-component:

import Masonry from 'react-masonry-component';

<Masonry
  elementType={'ul'}
  options={masonryOptions}
  disableImagesLoaded={false}
  updateOnEachImageLoad={false}
>
  {childElements}
</Masonry>

Isotope:

var iso = new Isotope('.grid', {
  itemSelector: '.grid-item',
  layoutMode: 'masonry'
});

// filter items
iso.arrange({ filter: '.metal' });

// change layout
iso.arrange({ layoutMode: 'fitRows' });

Summary

Isotope offers more features and flexibility but comes with licensing costs and potential integration challenges for React projects. react-masonry-component is simpler and React-specific but limited to masonry layouts. Choose based on project requirements and budget constraints.

Browser API's turned into declarative React components and HoC's

Pros of react-fns

  • Provides a wide range of utility functions and hooks for common React tasks
  • Offers a more comprehensive set of features beyond just layout components
  • Regularly updated and maintained, with active community support

Cons of react-fns

  • Not specifically designed for masonry layouts, requiring additional implementation
  • May include unnecessary features for projects focused solely on masonry layouts
  • Potentially larger bundle size due to its broader scope of functionality

Code Comparison

react-masonry-component:

import Masonry from 'react-masonry-component';

<Masonry
  elementType={'ul'}
  options={masonryOptions}
  disableImagesLoaded={false}
  updateOnEachImageLoad={false}
>
  {childElements}
</Masonry>

react-fns:

import { WindowSize } from 'react-fns';

<WindowSize>
  {({ width, height }) => (
    <div>
      Window size: {width} x {height}
    </div>
  )}
</WindowSize>

While react-masonry-component provides a ready-to-use masonry layout component, react-fns offers utility functions that can be used to build custom layouts, including masonry-style arrangements. The choice between the two depends on the specific project requirements and the desired level of customization.

Animated grid layout component for React

Pros of react-stonecutter

  • More flexible layout options, including grid, Pinterest-style, and custom layouts
  • Smoother animations and transitions between layout changes
  • Better performance for large numbers of items due to virtualization

Cons of react-stonecutter

  • Less actively maintained (last update was in 2018)
  • Steeper learning curve due to more complex API
  • Fewer stars and less community adoption compared to react-masonry-component

Code Comparison

react-masonry-component:

<Masonry>
  {items.map(item => (
    <div key={item.id}>{item.content}</div>
  ))}
</Masonry>

react-stonecutter:

<SpringGrid
  component="ul"
  columns={5}
  columnWidth={150}
  gutterWidth={5}
  gutterHeight={5}
  itemHeight={200}
  springConfig={{ stiffness: 170, damping: 26 }}
>
  {items.map(item => (
    <li key={item.id}>{item.content}</li>
  ))}
</SpringGrid>

The code comparison shows that react-stonecutter requires more configuration options, but offers greater control over the layout and animation behavior. react-masonry-component has a simpler API, making it easier to implement for basic use cases.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

React Masonry Component

npm version Build Status

IE8 support

if you wish to have IE8 support, v2 with React 0.14 is the highest version available.

Table of contents

  1. Usage
  2. Basic usage
  3. Custom props
  4. Accessing Masonry instance
  5. Images Loaded Options
  6. Events

Introduction:

A React.js Masonry component. (Also available as a mixin if needed)

Live demo:

hearsay.me

Usage:

  • The component is bundled with Masonry, so no additional dependencies needed!

  • You can optionally include Masonry as a script tag if there should be any reason for doing so <script src='//cdnjs.cloudflare.com/ajax/libs/masonry/3.1.5/masonry.pkgd.min.js' />

  • To use the component just require the module.

Basic usage

npm install --save react-masonry-component

import * as React from 'react';
import Masonry from 'react-masonry-component';

const masonryOptions = {
    transitionDuration: 0
};

const imagesLoadedOptions = { background: '.my-bg-image-el' }

class Gallery extends React.Component {
    render() {
        const childElements = this.props.elements.map(function(element){
           return (
                <li className="image-element-class">
                    <img src={element.src} />
                </li>
            );
        });
    
        return (
            <Masonry
                className={'my-gallery-class'} // default ''
                elementType={'ul'} // default 'div'
                options={masonryOptions} // default {}
                disableImagesLoaded={false} // default false
                updateOnEachImageLoad={false} // default false and works only if disableImagesLoaded is false
                imagesLoadedOptions={imagesLoadedOptions} // default {}
            >
                {childElements}
            </Masonry>
        );
    }
}

export default Gallery;

ES6-style modules are also supported, just use:

import Masonry from 'react-masonry-component';
Custom props

You can also include your own custom props - EG: inline-style and event handlers.

import * as React from 'react';
import Masonry from 'react-masonry-component';

const masonryOptions = {
    transitionDuration: 0
};

const style = {
    backgroundColor: 'tomato'
};

class Gallery extends React.Component {
    handleClick() {}
    render() {
        return (
            <Masonry
                className={'my-gallery-class'}
                style={style}
                onClick={this.handleClick}
            >
                {...}
            </Masonry>
        );
    }
}

export default Gallery;
Accessing Masonry instance

Should you need to access the instance of Masonry (for example to listen to masonry events) you can do so by using refs.

import * as React from 'react';
import Masonry from 'react-masonry-component';

class Gallery extends React.Component {
    handleLayoutComplete() { },

    componentDidMount() {
        this.masonry.on('layoutComplete', this.handleLayoutComplete);
    },

    componentWillUnmount() {
        this.masonry.off('layoutComplete', this.handleLayoutComplete);
    },

     render() {
         return (
             <Masonry
                 ref={function(c) {this.masonry = this.masonry || c.masonry;}.bind(this)}
             >
                 {...}
             </Masonry>
         );
     }
}

export default Gallery;
Images Loaded Options

React Masonry Component uses Desandro's imagesloaded library to detect when images have loaded. Should you want to pass options down to it then you need to populate the imagesLoadedOptions property on React Masonry Component.

This will most commonly be used when the elements in your gallery have CSS background images and you want to capture their load event. More info availabe on the imagesloaded website.

eg:

import * as React from 'react';
import Masonry from 'react-masonry-component';

class Gallery extends React.Component {
  render() {
    const imagesLoadedOptions = { background: '.my-bg-image-el' }
    
    return (
        <Masonry
            className={'my-gallery-class'}
            elementType={'ul'}
            options={masonryOptions}
            imagesLoadedOptions={imagesLoadedOptions}
        >
            <div className="my-bg-image-el"></div>
        </Masonry>
    );
  }
}

export default Gallery;
Events
  • onImagesLoaded - triggered when all images are loaded or after each image is loaded when updateOnEachImageLoad is set to true
  • onLayoutComplete - triggered after a layout and all positioning transitions have completed.
  • onRemoveComplete - triggered after an item element has been removed
class Gallery extends React.Component {
    componentDidMount() {
        this.hide();
    },
    handleImagesLoaded(imagesLoadedInstance) {
        this.show();
    },
    render() {
        return (
            <Masonry
                onImagesLoaded={this.handleImagesLoaded}
                onLayoutComplete={laidOutItems => this.handleLayoutComplete(laidOutItems)}
                onRemoveComplete={removedItems => this.handleRemoveComplete(removedItems)}
            >
                {...}
            </Masonry>
        )
    }
}

NPM DownloadsLast 30 Days