Erica Stockwell-Alpert Erica Stockwell-Alpert - 1 year ago 351
Javascript Question

React JS for loop inside rendering

I'm new to React JS and I'm not sure how to do a for loop to render something a variable number of times. This is my code:

<div className="product-selector__products">
{ this.props.products.sort(function(a,b) { return a.ranking - b.ranking }).map((p) => {

const className = "product" + ((this.props.selectedProductIds.indexOf( !== -1) ? " product--selected" : "");
const descriptionHtml = { __html: p.description };
const nameHtml = { __html: };

return (
<div className={className} key={ } onClick={this.onProductClick.bind(this,}>

<div className="product__image">
<img src={`/~/media/Bayer CropScience/Country-United-States-Internet/Comparison Tool/img/logos/${}_sm.png`} alt={} />
<div className="product__info">
<div className="product__name" dangerouslySetInnerHTML={nameHtml}></div>
<div className="product__description" dangerouslySetInnerHTML={descriptionHtml}></div>
<div className="product__message" ref={ }>
<div className="product__message-tooltip">Please remove a product<br/>before adding another</div>
<div className="product__message-triangle-down"></div>
}) }

/* Here I want to render <div className="product product--empty"> </div> a variable number of times*/


It generates a grid of product items, with 4 items per row.

I need to add empty divs onto the end of the last row so that each row has the same number of divs in it.

So if
this.props.products.length == 7
I need 1 empty div, and if I have 5 products I need 3 empty divs, etc.

The script i want is this:

let remainder = 4 - (this.props.products.length % 4);
for (let i = 0; i < remainder; i++){
return ( <div className="product product--empty"> </div> )

I'm not sure how to properly put this into the code-block though.

Answer Source

I've just modified a little Your code.

renderRemainders() {
  let products = []
  let remainder = 4 - (this.props.products.length % 4)

  for (let i = 0; i < remainder; i++){
    products.push( <div className="product product--empty"> </div> )

  return products

And just put

 { this.renderRemainders() }

somewhere in Your 'render' function.

Also, could You say something about why you need to render these empty rows?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download