Skip to content

Instantly share code, notes, and snippets.

@gustavoguichard
Created November 10, 2018 00:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gustavoguichard/f2bcab79355705d1d22da67ce48f5760 to your computer and use it in GitHub Desktop.
Save gustavoguichard/f2bcab79355705d1d22da67ce48f5760 to your computer and use it in GitHub Desktop.
Masonry react component
import React, { cloneElement, memo } from 'react'
import times from 'lodash/times'
const Masonry = ({ columns, children, ...props }) => (
<div {...props} className="masonry-tile">
{times(columns, index => (
<div className="vert-tile" key={`tile-${index}`}>
{React.Children.toArray(children)
.filter(
(child, filterIndex) =>
(filterIndex + index + (columns - 1)) % columns === 0,
)
.map((child, idx) =>
cloneElement(child, { ...child.props, key: idx }),
)}
</div>
))}
<style jsx>{`
.masonry-tile {
align-items: stretch;
display: flex;
flex-basis: 0;
flex-grow: 1;
flex-shrink: 1;
min-height: min-content;
}
.vert-tile {
align-items: stretch;
display: flex;
flex-basis: 0;
flex-grow: 1;
flex-shrink: 1;
min-height: min-content;
flex-direction: column;
}
`}</style>
</div>
)
export default memo(Masonry)
@gustavoguichard
Copy link
Author

gustavoguichard commented Nov 10, 2018

Usage:

const { width } = useWindowDimensions()
// nice effect, returns 4 columns for a 1280px screen
const columns = width ? Math.round(width / 365) : 2
return (
  <Masonry columns={columns}>
    {items.map((item, index) => (
      <Person key={index} {...item} />
    ))}
  </Masonry>
)

captura de tela 2018-11-09 as 22 27 19

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment