Let's say I have an array that looks like this:
const array = [0, 1, 2, 3, 4, 5, 6, 7]
What I'm trying to do is iterate for every 2 objects in a .map function, but it needs to look like something like this in my render (note that I'm using React Bootstrap):
<Row>
<Col>array[0]</Col>
<Col>array[1]</Col>
</Row>
<Row>
<Col>array[2]</Col>
<Col>array[3]</Col>
</Row>
etc...
So for every 2 objects, it needs to have it's own row, and then render those 2 objects before closing a Row and starting a new Row if it has more elements.
What's the best way to achieve this?
Transform model, then inject in View.
You need to convert your array to a matrix as per your need:
const array = [0, 1, 2, 3, 4, 5, 6, 7]
const rows = array.reduce(function (rows, key, index) {
return (index % 2 == 0 ? rows.push([key])
: rows[rows.length-1].push(key)) && rows;
}, []);
console.log(rows)
Now, you have your model is converted to this format
[ [0, 1] , [2, 3] , [4, 5] , [6, 7] ]
Now nested loop should do the job with elegance :
rows.map(row => (
<Row >
{ row.map(col => (<Col>{col}</Col>)) }
</Row>
))
The engineering behind this elegant solution is to prepare your model, then you loop.
Not sure, if React still requires id in (.e.g: <Compo id="">) when components are rendered in loop..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With