test
test

Reputation: 2466

React append 5 items in each div using for loop

I have this prop loop that pushes and shows 30 items

var newArr = [];
for (var key in this.props.data) {

     // for (var i = start; i < start + 5; i++) {
     //     if (i > array.length) return;

     //     $("#output").append(array[k]);
     // }

     newArr.push(<div><Dates key={key} /></div>);
}

I need to show this 5 items in a row so wrap it 5 items in each div like jQuery code that commented out possible ?

Upvotes: 0

Views: 1177

Answers (2)

ohsully
ohsully

Reputation: 502

The above answers work, so this is really just code golf, but here's my crack at it. Using forEach lets you not worry about miscalculation with an index, code accounts for having a non-full final row.

var newArr = [], row=[], rowLength=5;
this.props.data.forEach((item, index) => {
  row.push(item);
  if ((row.length === rowLength) || index === this.props.data.length - 1) {
    newArr.push(<div>{row}</div>);
    row = [];
  }
})

Upvotes: 0

Tomasz Mularczyk
Tomasz Mularczyk

Reputation: 36179

Probably not best algorithm out there but I think you want to do something like this:

var dates = [];
var rows = [];
for (var key in this.props.data) { 
  if (this.props.data.hasOwnProperty(prop)) {
    dates.push(<Dates key={key} />);

    if(dates.length === 5) {
      rows.push(
        <div>
          {dates}
        </div>
      );

      dates = [];
    }
  }
}

// final step
rows.push(
  <div>
    {dates}
  </div>
);

Upvotes: 2

Related Questions