1

I'm trying to integrate masonry.js in react.js and I'm having design problem.

Should I have all masonry blocks in one root react component like how it's done in react-masonry-component

<RootComponent>
    this.props.elements.map(function(element){
           return (
                <li className="image-element-class">
                    <img src={element.src} />
                </li>
            );
        });
<RootComponent>

Or should I have each masonry block as a new React component as child components of a root react component ?

<RootComponent>
    this.props.elements.map(function(element){
           return (
                <ChildComponent props={element}>
            );
        });
<RootComponent>
user794783
  • 3,619
  • 7
  • 36
  • 58

1 Answers1

-1

react-masonry-component is good if u want to use masonry always, but if you want to initialize masonry based on some condition, u can do as follows:

for example u fetch some items and then initialize masonry:

componentWillMount() {
    this.props.fetchItems();
}

componentDidUpdate(prevProps) {
    const {
        items
    } = this.props;

    if (this.state.masonry && prevProps.items !== items) { // reinitialize if items change
        $('.list').masonry('destroy');

        this.setState({
            masonry: false
        });
    }

    if (someCondition && items.length && !this.state.masonry) {
        $('.list').masonry({
            itemSelector: '.list__item'
        });

        this.setState({
            masonry: true
        });
    }
}

your render can look like this

render() {
const {
    items
} = this.props;
return (
    <div className="list">
        {items.map(item =>
            <div className="list__item" key={item.id} >
                {item.title}
            </div>
        )}
    </div>
);

}