Dinesh ghimire
Dinesh ghimire

Reputation: 25

How to break loop after 2nd element on react js inside map function

i have the followning element from map function and i want to break it into 2 element.

From this element:

<div class ="row">
<div class="col-md-3">1</div>
<div class="col-md-3">2</div>
<div class="col-md-3">3</div>
<div class="col-md-3">4</div>
</div>

TO:

<div class ="row">
<div class="col-md-3">1</div>
<div class="col-md-3">2</div>
</div>

<div class ="row">
<div class="col-md-3">3</div>
<div class="col-md-3">4</div>
</div>

Thank You!

React code:

{this.props.listdisplay
.filter(item => item.status === 1)
.map((item, i) => { 
    return <div className="col-md-3 col-sm-6" key={browse-by-${i}}> 
             <div className="food-block"> 
               <img src={item.icon} id={item.id} className="center-block img-responsive"/> 
                 <p className="text-center">
                   <a href="">{item.name}</a>
                 </p> 
             </div> 
          </div> 
}) }

Upvotes: 0

Views: 6133

Answers (1)

racz_gabor
racz_gabor

Reputation: 279

You could slice the arrays and map after them like this:

before return

let array = this.props.listdisplay.filter(item => item.status === 1);
let length = array.length;

in return

array.slice(0, (length + 1) / 2).map(.....)
array.slice((length + 1) / 2, length).map(.....)

The other thing if you want to create divs with two elements I can think of two solution (not a really beautiful solution though):

First: we creating the elements first before return:

var newList = [];
var array = this.props.listdisplay.filter(item => item.status === 1);
for (var i = 0; i < array.length + 1 / 2; i++) {
     var item = array[i];
     i++;
     var item2 = array[i];
     if (item2) {
         newList.push(<div class ="row">
                 <div class="col-md-3">item.id</div>
                 <div class="col-md-3">item2.id</div>
             </div>);
     } else {
         newList.push(<div class ="row">
                 <div class="col-md-3">item.id</div>
                 <div class="col-md-3">item2.id</div>
             </div>);
     }
}
return <div>{newList}</div>

Second: we can loop through the list and we always store the elements what are on odd index nr:

before return

var oddItem = null;

inside return:

{this.props.listdisplay.filter(item => item.status === 1).map((item, i) => {
    if (i%2 === 1) {
        oddItem= item;
    }

    return i%2 === 0 ? 
        <div class ="row">
            <div class="col-md-3">oddItem.id</div>
            <div class="col-md-3">item.id</div>
        </div> : '';
})}
/* If the array length is odd we remain one item in the oddItem so we need to add that too */
{this.props.listdisplay.filter(item => item.status === 1).length % 2 === 1 ? 
     <div class ="row">
         <div class="col-md-3">oddItem.id</div>
     </div>: ''}

Upvotes: 1

Related Questions