Skip to content

Instantly share code, notes, and snippets.

@nateabele
Created December 30, 2017 17:40
Show Gist options
  • Save nateabele/d981fcbda67f7440575169c2c9b61cda to your computer and use it in GitHub Desktop.
Save nateabele/d981fcbda67f7440575169c2c9b61cda to your computer and use it in GitHub Desktop.
class GridLayout extends React.Component {
resizeHandler = this.resizeAll.bind(this);
grid = null;
hasRendered = false;
componentDidMount() {
window.addEventListener('resize', this.resizeHandler);
}
componentWillUnmount() {
window.removeEventListener('resize', this.resizeHandler);
}
resizeAll() {
if (!this.grid) return;
this.grid.getElementsByClassName(this.props.itemClass || 'item').forEach(this.resize.bind(this));
}
resize(item) {
const style = window.getComputedStyle(this.grid), get = style.getPropertyValue.bind(style);
const rowHeight = parseInt(get('grid-auto-rows'), 10), rowGap = parseInt(get('grid-row-gap'), 10);
const bounds = item.querySelector(`.${this.props.contentClass || 'content'}`).getBoundingClientRect();
item.style.gridRowEnd = 'span ' + Math.ceil((bounds.height + rowGap) / (rowHeight + rowGap));
}
render() {
const { gridClass, children } = this.props;
if (!this.hasRendered) {
setTimeout(this.resizeAll.bind(this), 0);
this.hasRendered = true;
}
return (
<div className={gridClass || 'grid'} ref={el => this.grid = el}>
{children}
</div>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment