Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I map for every two elements for react?

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?

like image 755
Andrew Bautista Avatar asked Jul 17 '26 03:07

Andrew Bautista


1 Answers

short answer

Transform model, then inject in View.

Details answer

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>
))

NOTES:

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..

like image 60
Abdennour TOUMI Avatar answered Jul 18 '26 18:07

Abdennour TOUMI



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!