E
E
evg_962018-02-25 12:24:10
JavaScript
evg_96, 2018-02-25 12:24:10

How to make a grid with 4 elements per row in react+bootstrap?

There is a product catalog. The array of goods is obtained from the store. It is necessary to display all this in a grid of 4 elements per line and that everything be in the center and that each card be the same width. Tell me how to do this with a simple array of goods? It is not clear how to sort through the array to make rows (className="row")

Now I did this:

<div className="container">
  <div className="row">
    {
      this.props.catalog.map(product => (
        <Card
          className="col"
          key={product.uid}
          name={product.name}
          price={product.price}
          imageUrl={product.imageUrl}
          weight={product.weight}
          diameter={product.diameter}
        />
      ))
    }
  </div>
</div>

5a92811492bbb656111499.png

On the big screen, everything looks more or less normal. But again, not strictly 4 elements. And when the screen size is reduced, everything breaks ...
5a92822d0e94c095975174.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-02-25
@evg_96

It is necessary to display all this in a grid of 4 elements per line <...> It is not clear how to sort through the array to make lines

Obviously, cut the array into pieces of 4 elements, each will be a string:
const { items } = this.state;
const rows = [...Array(Math.ceil(items / 4))].map((n, i) => items.slice(i * 4, (i + 1) * 4));

And instead of the original array, when rendering, iterate over the resulting pieces:
{rows.map(n => (
  <div className="row">
    {n.map(m => <div>{m}</div>)}
  </div>
))}

https://jsfiddle.net/mf6n14tx/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question