1

I have the render method in a react component shown below, which displays a 4 by 4 grid.

I want to split the products into groups of 4, how can I do this?

For example if I have 12 products, 3 groups of 4, I need to display

XXXX

XXXX

XXXX

I could have productList1, productList2, productList3, but I need it to be extensible, for instance the grid may take 40 products, so would be a 10 x 4 grid.

render() {

  let productList = this.props.products.map( (p, i) => {
    if(i < 4){
      return (
        <ul key={i}><li>{p.name}</li></ul>
      );
    } else {
      return (
        <span>not sure</span>
      );
    }
  });

  return (
    <section>          
      {/* 4 products */}
      <div className="row">
        {productList}
      </div>

      {/* the next 4 */}
      <div className="row"> 
        {productList2}
      </div>

      {/* and the next 4 */}
      <div className="row"> 
        {productList3}
      </div>
    </section>   
  )
}
7
  • 2
    Is there a reason not to do it in CSS? Commented Aug 14, 2015 at 3:08
  • 1
    Yeah, no, you cannot use map to do that. Commented Aug 14, 2015 at 3:10
  • yes unfortunately as I am rewriting a drupal site to react on this occasion I want to keep the html structure the same if possible. Commented Aug 14, 2015 at 3:28
  • 1
    If you're rewriting then I'd add a css lib like Pure from Yahoo where you can specify grids and grid units and just add the css class for it. Commented Aug 14, 2015 at 5:22
  • 1
    You don't have to rewrite the whole site to add a CSS grid for your products. It will take far less time to implement this correctly than couple layout in your JSX that you just have to fix down the road... Commented Aug 14, 2015 at 6:47

1 Answer 1

2

While what you want is not possible, here is a decent (I think) solution.

var allProds = yourProds,
    prodList = [], i,
    products = [];
for (i = 0; i < allProds.length; i++) {
    if (i % 4 ===0) {
       products.push(prodList);
       prodList = [];
    }
    prodList.push(allProds[i]);
}

This is untested

Then, when returning the html, you can loop through each array in the products array and output them four at a time.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.