Skip to content Skip to sidebar Skip to footer

ReactJS How To Render 4 Items In A Row (items From Api)

I am retrieving a list of posts from my API and i'd like to arrange them such as ->

Solution 1:

First, group the items based on row where they will be placed, then iterate over the grouped data and render 4 items per row. Please consider following code snippets

Creating group data using reduce method

componentDidMount() {
  ...
  .then(data => {
     var grouped = data.reduce((acc, post, ind) => {
       var index = parseInt(ind / 4);
       acc[index]= acc[index] || []; 
       acc[index].push(<Col > /*Column definition goes here*/ </Col>);
       return acc;
     }, {});
     this.setState({ grouped });
  });
}

Once you have the grouped data, you can render it as follows

render() {
  const { grouped } = this.state;
  return (
    <React.Fragment>
      {
        Object.keys(grouped).map(row => {
          return (
            <Row>
            {
              grouped[row]
            }
            </Row>
          );
        })
      }
    </React.Fragment>
  );
}

Hope this will help!


Post a Comment for "ReactJS How To Render 4 Items In A Row (items From Api)"