Created
November 10, 2018 00:16
-
-
Save gustavoguichard/f2bcab79355705d1d22da67ce48f5760 to your computer and use it in GitHub Desktop.
Masonry react component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: