Languages
[Edit]
EN

React - create grid using flexbox

0 points
Created by:
Saim-Mccullough
718

In this article, we would like to show you how to create a grid using flexbox in React.

Practical example

In this example, to generate grid cells we use nested for loops.

For the grid style, we need to set display property  value to flex and for columns, we need to set flex: 1 so each column will fill the same amount of space.

// ONLINE-RUNNER:browser;

// Note: uncomment import lines in yours project.
// import React from "react";
// import ReactDOM from "react-dom";

const gridStyle = {
    display: 'flex' /* <--- required */,
};

const columnStyle = {
    flex: 1 /* <--- required */,
};

const rowStyle = {
    margin: '2px',
    background: 'gold',
    textAlign: 'center',
};

const Grid = ({columnsCount, rowsCount}) => {
    const columns = Array(columnsCount);
    for (let i = 0; i < columnsCount; ++i) {
        const rows = Array(rowsCount);
        for (let j = 0; j < rowsCount; ++j) {
            rows[j] = (<div key={j} style={rowStyle}>{i}-{j}</div>);
        }
        columns[i] = (<div key={i} style={columnStyle}>{rows}</div>);
    }
    return <div style={gridStyle}>{columns}</div>;
};


// Usage example:

const App = () => {
    return <Grid columnsCount={3} rowsCount={4} />;
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

Example 2

// ONLINE-RUNNER:browser;

// Note: uncomment import lines in yours project.
// import React from "react";
// import ReactDOM from "react-dom";


const gridStyle = {
    padding: '2px 0 0 2px',
    display: 'inline-flex',
};

const rowStyle = {
    margin: '0 2px 2px 0',
    background: 'gold',
};

const Grid = ({ cellStyle, columnsCount, rowsCount }) => {
    const columns = Array(columnsCount);
    for (let i = 0; i < columnsCount; ++i) {
        const rows = Array(rowsCount);
        for (let j = 0; j < rowsCount; ++j) {
            rows[j] = <div key={j} style={{ ...cellStyle, ...rowStyle }}></div>;
        }
        columns[i] = <div key={i}>{rows}</div>;
    }
    return <div style={gridStyle}>{columns}</div>;
};


// Usage example:

const App = () => {
    return <Grid cellStyle={{ width: '25px', height: '25px' }} columnsCount={5} rowsCount={5} />;
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join