Diego Unanue
Diego Unanue

Reputation: 6826

Map with bootstrap columns

I'm using map to iterate throug a list of elements, what I want is to have 4 elements per row. This is my render part of the class:

render() {
    return (
      <div>
        <h1>Card List</h1>

        {this.props.items ? this.props.items.map((item) =>
          <div class="cardSection">
            <Row className="show-grid">
                <Card name={item.name} imgGold={item.imgGold}  />
            </Row>
          </div>

        ) : <div>Loading!</div>}

      </div>
    )
  }
}

I want 4 Card components per row using xs={4} md={4}

Upvotes: 2

Views: 1857

Answers (1)

Jo&#227;o Cunha
Jo&#227;o Cunha

Reputation: 10307

You can do something like

const items = [
  { name: "1" },
  { name: "2" },
  { name: "3" },
  { name: "4" },
  { name: "5" },
  { name: "6" },
  { name: "7" },
  { name: "8" },
  { name: "9" },
  { name: "10" },
  { name: "11" },
];

const App = () => {
  const result = items.map((x,i) => {
      return i % 4 === 0 ? items.slice(i, i+4) : null;
  }).filter(x => x != null);

  return (
    <div>
      {result.map((result, index) => {
        return (<section key={index}>
          {result.map(item => <span>{item.name}</span>)}
        </section>);
       })}
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));
span {
 margin-left: 5px;
 margin-right: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>

This will group your item array into groups of 4. You can even make it accept any number you want.

You can then iterate and render each of them in groups of 4.

Please make sure you run the snippet so you can see it working.

Upvotes: 6

Related Questions