react-responsive-masonry

repository·master·Indexed 19 days ago

https://github.com/cedricdelpoux/react-responsive-masonry

A React component library for creating responsive masonry layouts using CSS flexbox. It provides a Masonry component for static layouts and a ResponsiveMasonry wrapper to dynamically adjust column counts and gutter sizes based on viewport breakpoints.

Tokens
3.8K
Snippets
10
Records
13
Agent score
65%

What's inside react-responsive-masonry

  1. How ResponsiveMasonry and Masonry work together

    master

    To create a masonry layout where the number of columns and the gutter size change based on the window size, you must wrap the Masonry component with the ResponsiveMasonry component.

    If you want a static layout where the column count remains constant regardless of screen size, use the Masonry component alone.

    Responsive Layout Example

    import React from "react"
    import Masonry, {ResponsiveMasonry} from "react-responsive-masonry"
    
    const MyWrapper = () => (
        <ResponsiveMasonry
            columnsCountBreakPoints={{350: 1, 750: 2, 900: 3}}
            gutterBreakPoints={{350: "12px", 750: "16px", 900: "24px"}}
        >
            <Masonry>
                <ChildA />
                <ChildB />
                <ChildY />
                <ChildZ />
            </Masonry>
        </ResponsiveMasonry>
    )

    Static Layout Example

    import React from "react"
    import Masonry from "react-responsive-masonry"
    
    const MyWrapper = () => (
        <Masonry columnsCount={3}>
            <ChildA />
            <ChildB />
            <ChildY />
            <ChildZ />
        </Masonry>
    )
    import React from "react"
    import Masonry, {ResponsiveMasonry} from "react-responsive-masonry"
    
    // The number of columns and the gutter change by resizing the window
    class MyWrapper extends React.Component {
        render() {
            return (
                <ResponsiveMasonry
                    columnsCountBreakPoints={{350: 1, 750: 2, 900: 3}}
                    gutterBreakPoints={{350: "12px", 750: "16px", 900: "24px"}}
                >
                    <Masonry>
                        <ChildA />
                        <ChildB />
                        {/* Children */}
                        <ChildY />
                        <ChildZ />
                    </Masonry>
                </ResponsiveMasonry>
            )
        }
    }
    
    // The number of columns and the gutter don't change by resizing the window
    class MyWrapper extends Component {
        render() {
            return (
                <Masonry columnsCount={3}>
                    <ChildA />
                    <ChildB />
                    {/* Children */}
                    <ChildY />
                    <ChildZ />
                </Masonry>
            )
        }
    }
  2. Install react-responsive-masonry

    master

    You can install react-responsive-masonry via npm or yarn. If you prefer not to use a package manager, you can include it directly in your HTML using the UNPKG CDN.

    yarn add react-responsive-masonry
    npm install react-responsive-masonry --save
    https://unpkg.com/react-responsive-masonry/umd/react-responsive-masonry.js
  3. Use the Masonry component

    master

    The Masonry component from react-responsive-masonry allows you to create a masonry layout for your items. You can specify the number of columns using the columnsCount prop and the spacing between items using the gutter prop.

    Note: In the basic Masonry component, the columnsCount does not change dynamically; it remains fixed to the value provided.

    import React from "react"
    import Masonry from "react-responsive-masonry"
    
    const images = [
        "https://picsum.photos/200/300?image=1050",
        //...
        "https://picsum.photos/300/300?image=206",
    ]
    
    class MyWrapper extends React.Component {
        render() {
            return (
                <Masonry columnsCount={3} gutter="10px">
                    {images.map((image, i) => (
                        <img
                            key={i}
                            src={image}
                            style={{width: "100%", display: "block"}}
                        />
                    ))}
                </Masonry>
            )
        }
    }
  4. Use ResponsiveMasonry to create a responsive masonry layout

    master

    To create a masonry layout where the number of columns and the gutter size change dynamically based on the viewport width, wrap a Masonry component with the ResponsiveMasonry component.

    ResponsiveMasonry acts as a provider that injects responsive configuration into its child Masonry component using the following props:

    • columnsCountBreakPoints: An object where keys are viewport widths (in pixels) and values are the number of columns to display at that width or larger.
    • gutterBreakPoints: An object where keys are viewport widths (in pixels) and values are the CSS gutter size (e.g., '5px', '1rem') to apply at that width or larger.
    import React from "react"
    import Masonry, {ResponsiveMasonry} from "react-responsive-masonry"
    
    const images = [
        "https://picsum.photos/200/300?image=1050",
        //...
        "https://picsum.photos/300/300?image=206",
    ]
    
    class MyWrapper extends React.Component {
        render() {
            return (
                <ResponsiveMasonry
                    columnsCountBreakPoints={{350: 1, 750: 2, 900: 3}}
                    gutterBreakPoints={{350: "5px", 750: "16px", 900: "2rem"}}
                >
                    <Masonry>
                        {images.map((image, i) => (
                            <img
                                key={i}
                                src={image}
                                style={{width: "100%", display: "block"}}
                                alt=""
                            />
                        ))}
                    </Masonry>
                </ResponsiveMasonry>
            )
        }
    }
  5. Configure the nwb build for react-responsive-masonry

    master

    The project uses nwb for its build configuration. The nwb.config.js defines how the package is bundled for different environments (CJS, ESM, UMD) and how Webpack handles specific file types.

    Key configuration settings include:

    • type: Set to react-component.
    • npm: Configures output formats. It enables both cjs and esModules. The umd build uses the global name ReactResponsiveMasonry and treats react and prop-types as externals.
    module.exports = {
      type: "react-component",
      npm: {
        cjs: true,
        esModules: true,
        umd: {
          global: "ReactResponsiveMasonry",
          externals: {
            react: "React",
            "prop-types": "PropTypes",
          },
        },
      },
      webpack: {
        extra: extraWebpackConfig,
      },
    }
  6. How ResponsiveMasonry calculates responsive values

    master

    The component uses a breakpoint-based logic to determine values for columnsCount and gutter.

    1. It monitors the window.innerWidth via a resize listener.
    2. It sorts the keys of your breakpoint objects (e.g., columnsCountBreakPoints) in ascending order.
    3. It iterates through the sorted breakpoints. If a breakpoint is less than the current windowWidth, the corresponding value is selected.
    4. If no breakpoints match or the object is empty, it falls back to the default values:
      • Default columnsCount: 1
      • Default gutter: `
  7. Masonry component props

    master

    The Masonry component is the core container for your masonry items. It can be used standalone or wrapped by ResponsiveMasonry.

    | Name | PropType | Description | Default |
    | ------------ | -------- | ------------------------------------------------------ | ------- |
    | columnsCount | Number | Injected by ResponsiveMasonry | 3 |
    | gutter | String | Margin surrounding each item e.g. "10px" or "1.5rem" | "0" |
    | className | String | Custom CSS class applied to the container element | null |
    | style | Object | Style object for customizing the container element | {} |
    | containerTag | String | Tag name of the container element | "div" |
    | itemTag | String | Tag name of the item element | "div" |
    | itemStyle | Object | Style object applied to each item | {} |
    | sequential | Boolean | If true, items are placed in the order they are passed | false |
  8. ResponsiveMasonry component props

    master

    The ResponsiveMasonry component provides the logic for adjusting the layout based on viewport breakpoints.

    | Name | PropType | Description | Default |
    | ----------------------- | -------- | -------------------------------------------------------- | ------------------------ |
    | columnsCountBreakPoints | Object | Keys are breakpoints in px, values are the columns number | {350: 1, 750: 2, 900: 3} |
    | gutterBreakPoints | Object | Keys are breakpoints in px, values are the gutter value in any valid CSS value for 'gap' | |
  9. Use the ResponsiveMasonry component

    master

    The ResponsiveMasonry component is a wrapper that manages masonry layout properties (columns and gutters) based on the current window width. It automatically calculates the appropriate columnsCount and gutter size using provided breakpoints and injects these values into its children via React.cloneElement.

    To use it, wrap your masonry items (which must be able to receive columnsCount and gutter props) inside the ResponsiveMasonry component.

    import ResponsiveMasonry from 'react-responsive-masonry';
    
    // Example usage:
    <ResponsiveMasonry columnsCountBreakPoints={{ 640: 1, 768: 2, 1024: 3 }}>
      {items.map(item => (
        <MasonryItem key={item.id} />
      ))}
    </ResponsiveMasonry>
  10. Configure Masonry component props

    master

    The Masonry component accepts the following props to control its layout and appearance:

    PropTypeDefaultDescription
    childrennode or Array<node>RequiredThe items to be laid out in the masonry grid.
    columnsCountnumber3The number of columns to render.
    gutterstring"0"The spacing (gap) between columns and between items within a column.
    sequentialbooleanfalseIf true, items are distributed sequentially (1, 2, 3...) instead of being placed in the shortest column.
    containerTagstring"div"The HTML tag used for the outer container.
    itemTagstring"div"The HTML tag used for each column.
    classNamestringnullCSS class name for the container.
    styleobject{}Inline styles for the container.
    itemStyleobject{}Inline styles for each column.
  11. Configure ResponsiveMasonry props

    master

    The ResponsiveMasonry component accepts the following props to control its responsive behavior:

    PropTypeDefaultDescription
    childrennode or arrayOf(node)RequiredThe masonry items to be rendered. Each child will receive columnsCount and gutter as props.
    columnsCountBreakPointsobject{ 350: 1, 750: 2, 900: 3 }An object mapping window width breakpoints (as numbers) to the number of columns. Example: { 600: 1, 900: 2 }.
    gutterBreakPointsobject{}An object mapping window width breakpoints (as numbers) to gutter sizes (strings). Example: { 600: '10px', 900: '20px' }.
    classNamestringnullCSS class name for the container div.
    styleobjectnullInline styles for the container div.