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(p.id) !== -1) ? " product--selected" : "");
const descriptionHtml = { __html: p.description };
const nameHtml = { __html: p.name };
return (
<div className={className} key={ p.id } onClick={this.onProductClick.bind(this, p.id)}>
<div className="product__image">
<img src={`/~/media/Bayer CropScience/Country-United-States-Internet/Comparison Tool/img/logos/${p.id}_sm.png`} alt={p.name} />
</div>
<div className="product__info">
<div className="product__name" dangerouslySetInnerHTML={nameHtml}></div>
<div className="product__description" dangerouslySetInnerHTML={descriptionHtml}></div>
</div>
<div className="product__message" ref={ p.id }>
<div className="product__message-tooltip">Please remove a product<br/>before adding another</div>
<div className="product__message-triangle-down"></div>
</div>
</div>
);
}) }
/* Here I want to render <div className="product product--empty"> </div> a variable number of times*/
</div>
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.
this.props.products.slice(0, 4).map?this.props.products.slice(-this.props.products.length % 4, this.props.products.length % 4 ? undefined : 0).map(() => <div className="product product--empty"/>), maybe it's better to assignthis.props.products.length % 4to variable first