Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: Render new row every 4th column

I'm using react and I want to render a new row every 4th column.

My code:

function Product(props) {
  const content = props.products.map((product) => (
        <div className="row" key={product.id}>       
          <article key={product.id} className="col-md-3"></article>
        </div> )
  );
  return (
    <div>
        {content}
    </div>
  );
}

I tried with the approach by passing in a condition that looked like this:

if (product.id % 4 == 1), around the columns, but it doesn't work...

This is what I want to happen:

<div class="row">
<div class="col-md-3"></div>
<div class="col-md-3"></div>
<div class="col-md-3"></div>
<div class="col-md-3"></div>
</div>
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-3"></div>
<div class="col-md-3"></div>
<div class="col-md-3"></div>
</div>
like image 755
maverick Avatar asked Feb 22 '17 12:02

maverick


1 Answers

  1. Group your products into rows of (at most) 4 elements, i.e.

    [1,2,3,4,5,6,7,8] => [ [1, 2, 3, 4], [5, 6, 7, 8 ] ]

  2. Iterate over the groups to generate rows, and in an inner loop iterate over the items to display columns

To calculate the number of rows, given 4 items per row, use Math.ceil(props.products.length / 4). Then create an array of rows. Given 2 rows (for 8 items): Array(2). Since you can't map an array of uninitialized elements, you can use spread syntax: [...Array(2)] which returns [ undefined, undefined ].

Now you can map these undefined entries into rows: for each row take 4 elements from products: [ undefined, undefined ].map( (row, idx) => props.products.slice(idx * 4, idx * 4 + 4) ) ) (edit note changed to slice since splice mutates the original array). The result is an array of arrays (rows of items).

You can iterate over the rows, and inside each iteration iterate over the items in given row.

https://jsfiddle.net/dya52m8y/2/

const Products = (props) => {
    // array of N elements, where N is the number of rows needed
    const rows = [...Array( Math.ceil(props.products.length / 4) )];
    // chunk the products into the array of rows
    const productRows = rows.map( (row, idx) => props.products.slice(idx * 4, idx * 4 + 4) ); );
    // map the rows as div.row
    const content = productRows.map((row, idx) => (
        <div className="row" key={idx}>    
          // map products in the row as article.col-md-3
          { row.map( product => <article key={product} className="col-md-3">{ product }</article> )}
        </div> )
    );
    return (
        <div>
          {content}
        </div>
    );
}
like image 184
pawel Avatar answered Sep 20 '22 07:09

pawel