Home > Back-end >  how do i divide grid by number of element?
how do i divide grid by number of element?

Time:09-26

const value = [1, 2, 3, 4, 5, 6, 7];

I want

1 2 3

4 5 6

7

---Row configuration---

<Row>
  <Col/>
  <Col/>
  <Col/>
</Row>

How can I make it like above?

Also, I hope it will continue to be applied even if the number is added to the list.

CodePudding user response:

With a good ol' for loop.

function Component() {
  const value = [1, 2, 3, 4, 5, 6, 7];
  const numPerRow = 3;
  const rows = [];
  for (let i = 0; i < value.length; i  = numPerRow) {
    const slice = value.slice(i, i   numPerRow);
    rows.push(
      <Row key={i}>
        {slice.map((value) => (
          <Col key={value}>{value}</Col>
        ))}
      </Row>,
    );
  }
  return <>{rows}</>;
}

You can of course make this a more functional-y helper:

function mapSlices(arr, sliceLength, fn) {
  const output = [];
  for (let i = 0; i < arr.length; i  = sliceLength) {
    output.push(fn(arr.slice(i, i   sliceLength), i));
  }
  return output;
}

function Component() {
  const value = [1, 2, 3, 4, 5, 6, 7];
  return (
    <>
      {mapSlices(value, 3, (slice, i) => (
        <Row key={i}>
          {slice.map((value) => (
            <Col key={value}>{value}</Col>
          ))}
        </Row>
      ))}
    </>
  );
}
  • Related