React: Render new row every 4th column
write it like this:
function Product(props) {
let content = [];
props.products.forEach((product, i) =>{
if((i+1) % 4 == 0){
content.push(
<div className="row" key={product.id}>
<article key={product.id} className="col-md-3"></article>
</div>
)
}else{
content.push(<article key={product.id} className="col-md-3"></article>);
}
});
return (
<div>
{content}
</div>
);
}
Group your products into rows of (at most) 4 elements, i.e.
[1,2,3,4,5,6,7,8] => [ [1, 2, 3, 4], [5, 6, 7, 8 ] ]
Iterate over the groups to generate rows, and in an inner loop iterate over the items to display columns
To calculate the number of rows, given 4 items per row, use Math.ceil(props.products.length / 4)
. Then create an array of rows. Given 2 rows (for 8 items): Array(2)
. Since you can't map
an array of uninitialized elements, you can use spread syntax: [...Array(2)]
which returns [ undefined, undefined ]
.
Now you can map these undefined
entries into rows: for each row take 4 elements from products: [ undefined, undefined ].map( (row, idx) => props.products.slice(idx * 4, idx * 4 + 4) ) )
(edit note changed to slice
since splice
mutates the original array). The result is an array of arrays (rows of items).
You can iterate over the rows, and inside each iteration iterate over the items in given row.
https://jsfiddle.net/dya52m8y/2/
const Products = (props) => {
// array of N elements, where N is the number of rows needed
const rows = [...Array( Math.ceil(props.products.length / 4) )];
// chunk the products into the array of rows
const productRows = rows.map( (row, idx) => props.products.slice(idx * 4, idx * 4 + 4) ); );
// map the rows as div.row
const content = productRows.map((row, idx) => (
<div className="row" key={idx}>
// map products in the row as article.col-md-3
{ row.map( product => <article key={product} className="col-md-3">{ product }</article> )}
</div> )
);
return (
<div>
{content}
</div>
);
}