Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: Loop over data and create rows with three items in a row

I have an array of items, 9 be exact attached to my state:

 state =  {
    menuItems: [
        {
            id: 0,
            name: 'Foods',
            iconSrc: 'food.jpg'
        },
        {
            id: 1,
            name: 'Drinks',
            iconSrc: 'drinks.jpg'
        },
        {
            id: 2,
            name: 'Snacks',
            iconSrc: 'snacks.jpg'
        }
   ]

and want to loop over them, however i have 9 items in the array and want to do the following: group every three items in the array under a new div, like so:

<div class="row-container">
   <div class="col-4">
        <div class="col-2">Item 1</div>
        <div class="col-2">Item 2</div>
        <div class="col-2">Item 3</div>
    </div>
    <div class="col-4">
        <div class="col-2">Item 4</div>
        <div class="col-2">Item 5</div>
        <div class="col-2">Item 6</div>
    </div>
    <div class="col-4">
        <div class="col-2">Item 7</div>
        <div class="col-2">Item 8</div>
        <div class="col-2">Item 9</div>
    </div>
</div>

How do I achieve that using the map function within React?

like image 435
Beto Avatar asked Sep 08 '26 09:09

Beto


1 Answers

You can get use of modulus(Reminder). Modulus will tell you the reminder of the division for given integer.

The remainder operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend, not the divisor. It uses a built-in modulo function to produce the result, which is the integer remainder of dividing var1 by var2

Example

this.state.menuItems.map((item, index) => {
  if (((index + 1) % 3) === 1) {

    return (
      <div className="col-4">
      <div className="col-2">{item.name}</div>
    );

  } else if (((index + 1) % 3) === 2) {

    return (<div className="col-2">{item.name}</div>);

  } else if (((index + 1) % 3) === 0) {

    return (
      <div className="col-2">{item.name}</div>
      </div>
    );

  }
});
like image 156
bennygenel Avatar answered Sep 10 '26 21:09

bennygenel



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!