Search code examples
reactjsgridreact-bootstrap

Align array from map() to rows and columns


I created an array of numbers and I used the map() to display it. But I want to align it in 9 rows and 5 columns. Example display in the picture (don't consider the labels of the checkboxes. I just want to sort the checkboxes like that).

This is the example

Here is my code:

import React from 'react';
import { Row , Form, Container} from 'react-bootstrap';

const KlassiSelector = () => {
    const ArrayKlassis = [];
    for(let i=1; i<46; i++){
        ArrayKlassis.push(i);
    }

    return (
            <Row className="m-2">

                <div key="Klassis-Section" className="m-2 justify-content-md-center">
                
                {ArrayKlassis.map((item, index) => (
                    <Form.Check inline label={`${index+1}`} name="group1" type="checkbox" id={`inline-checkbox-${index+1}`}/>
                ))}
                </div>

            </Row>
    );
};

export default KlassiSelector;

Solution

  • import React from "react";
    import { Row, Form, Container } from "react-bootstrap";
    
    const KlassiSelector = () => {
      return (
        <>
          {[...new Array(9)].map((row, rowIndex) => {
            return (
              <Row className="m-2" key={rowIndex}>
                <div
                  key="Klassis-Section"
                  className="m-2 justify-content-md-center"
                >
                  {[...new Array(5)].map((col, colIndex) => {
                    const crrIndex = rowIndex + colIndex * 9 + 1;
                    return (
                      <Form.Check
                        key={colIndex}
                        inline
                        label={`${crrIndex}`}
                        name="group1"
                        type="checkbox"
                        id={`inline-checkbox-${crrIndex}`}
                      />
                    );
                  })}
                </div>
              </Row>
            );
          })}
        </>
      );
    };
    
    export default KlassiSelector;
    

    Hope this would be helpful for you.