Tom Pinchen
Tom Pinchen

Reputation: 2497

Bootstrap Rows in ReactJS

I am working with a reactJS app and have the following code:

renderProductBlock(product, index) {
    return (
        <div className="product col-xs-4">
            <span className="product-name">{product.name}</span>
            <span className="product-price">{product.price}</span>
            <a href="#" className="btn btn-primary">Buy Now</a>
        </div>
    );
}

renderProductList() {
    let blocks = [];

    _.forEach(product, (item, index) => {
        const productBlock = this.renderProductBlock(item, index);

        if(productBlock) {
            blocks.push(productBlock);
        }
    });

    return blocks;
}

render() {
    const productsBlock = this.renderProductList();

    if(productsBlock) {
        return (
            <div className="products">
                <div className="row">
                  {productsBlock}
                </div>
            </div>
        )
    }   
}

Which is outputting HTML in this layout:

<div class="products">
    <div class="row">
      <div class="product col-xs-4">
          Content
      </div>
      <div class="product col-xs-4">
          Content
      </div>
      <div class="product col-xs-4">
          Content
      </div>
      <div class="product col-xs-4">
          Content
      </div>
      <div class="product col-xs-4">
          Content
      </div>
   </div>
</div>

What would be the best way for me to add bootstrap rows into these loops to wrap every 3 products in a row div like so:

<div class="products">
    <div class="row">
        <div class="product col-xs-4">
            Content
        </div>
        <div class="product col-xs-4">
            Content
        </div>
        <div class="product col-xs-4">
            Content
        </div>
    </div>
    <div class="row">
        <div class="product col-xs-4">
            Content
        </div>
        <div class="product col-xs-4">
            Content
        </div>
    </div>
</div>

Sorry for the slightly simple question but I can't seem to get this right.

Upvotes: 1

Views: 1575

Answers (1)

Aleph Aleph
Aleph Aleph

Reputation: 5395

Would just keep track of the how many blocks have been processed within the loop and once three blocks are rendered, group them in a row:

renderRow() {
    return (
        <div class="row">
            {block}
        </div>
    );
}

renderProductList() {
    let blocks = [], rows = [];
    _.forEach(product, (item, index) => {
        const productBlock = this.renderProductBlock(item, index);
        if (productBlock) {
            blocks.push(productBlock);
        }
        if (block.length >= 3) {
            const row = this.renderRow(blocks);
            if (row) {
                rows.push(row);
            }
            blocks = [];
        }
    });    
    const row = this.renderRow(blocks);
    if (row) {
         rows.push(row); 
    }
    return rows;
}

Upvotes: 5

Related Questions