Reputation: 3651
I have data being extracted from an external api. I want to map this data to SimpleCards component and loop it and render it using bootstrap grid. Meaning for every row, I wish to have 4 columns (or 2 columns for smaller devices). How would I loop and create this dynamically? Can't get my head around this and trying to do the following which is currently not working. Appreciate any help or a better way to do this. Thank you.
After looping, I would like it to have rendered as following:
<div className="row">
<div className="col-md-6 col-sm-6 col-lg-3 format">
<SimpleCard/>
</div>
<div className="col-md-6 col-sm-6 col-lg-3 format">
<SimpleCard/>
</div>
<div className="col-md-6 col-sm-6 col-lg-3 format">
<SimpleCard/>
</div>
<div className="col-md-6 col-sm-6 col-lg-3 format">
<SimpleCard/>
</div>
</div>
<div className="row">
<div className="col-md-6 col-sm-6 col-lg-3 format">
<SimpleCard/>
</div>
<div className="col-md-6 col-sm-6 col-lg-3 format">
<SimpleCard/>
</div>
<div className="col-md-6 col-sm-6 col-lg-3 format">
<SimpleCard/>
</div>
<div className="col-md-6 col-sm-6 col-lg-3 format">
<SimpleCard/>
</div>
</div>
<div className="row">
<div className="col-md-6 col-sm-6 col-lg-3 format">
<SimpleCard/>
</div>
<div className="col-md-6 col-sm-6 col-lg-3 format">
<SimpleCard/>
</div>
<div className="col-md-6 col-sm-6 col-lg-3 format">
<SimpleCard/>
</div>
<div className="col-md-6 col-sm-6 col-lg-3 format">
<SimpleCard/>
</div>
</div>
I am trying to achieve the above via a loop as following (in above example I am show 12 repetitions. When I am making actual call I would be getting a lot more thus not practical to be hard coding it):
This doesn't work, I end up seeing nothing. To be honest I don't think it makes sense thus not surprised but unable to figure out a way to loop it right. Please assist.
const CardList = props => {
const list = [0,1,2,3,4,5,6,7,8,9,10,11,12]; // just faking to get 12 interations.
// in actual case this would be an api call's result.
return (
<div className="row">
{
list.forEach((item, index) => {
if (index % 4 === 0 && index !== 0){
return (
<div className="row">
<div className="col-md-6 col-sm-6 col-lg-3 format">
<SimpleCard/>
</div>
</div>
)
} else {
return (
<div className="col-md-6 col-sm-6 col-lg-3 format">
<SimpleCard/>
</div>
)
}
})
}
</div>
);
}
export default CardList;
Upvotes: 2
Views: 2381
Reputation: 106
What you're doing here is, you are creating an entire row with just one card for every fourth array element.
What you need is to group elements into rows. One possible way is to group them with a function like this:
function chunkArray(arr, size) {
var groupedArray = [];
for(var i = 0; i < arr.length; i += size) {
groupedArray.push(arr.slice(i, i+size));
}
return groupedArray ;
}
Now you can have nested mapping:
return (
chunkArray(list, 4).map(
chunk =>
<div class="row">
{chunk.map(item =>
<div className="col-md-6 col-sm-6 col-lg-3 format">
<SimpleCard/>
</div>
)}
</div>
)
);
Upvotes: 1