EN
React - create grid using flexbox
0 points
In this article, we would like to show you how to create a grid using flexbox in React.
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.
xxxxxxxxxx
1
// Note: uncomment import lines in yours project.
2
// import React from "react";
3
// import ReactDOM from "react-dom";
4
5
const gridStyle = {
6
display: 'flex' /* <--- required */,
7
};
8
9
const columnStyle = {
10
flex: 1 /* <--- required */,
11
};
12
13
const rowStyle = {
14
margin: '2px',
15
background: 'gold',
16
textAlign: 'center',
17
};
18
19
const Grid = ({columnsCount, rowsCount}) => {
20
const columns = Array(columnsCount);
21
for (let i = 0; i < columnsCount; ++i) {
22
const rows = Array(rowsCount);
23
for (let j = 0; j < rowsCount; ++j) {
24
rows[j] = (<div key={j} style={rowStyle}>{i}-{j}</div>);
25
}
26
columns[i] = (<div key={i} style={columnStyle}>{rows}</div>);
27
}
28
return <div style={gridStyle}>{columns}</div>;
29
};
30
31
32
// Usage example:
33
34
const App = () => {
35
return <Grid columnsCount={3} rowsCount={4} />;
36
};
37
38
const root = document.querySelector('#root');
39
ReactDOM.render(<App />, root );
xxxxxxxxxx
1
// Note: uncomment import lines in yours project.
2
// import React from "react";
3
// import ReactDOM from "react-dom";
4
5
6
const gridStyle = {
7
padding: '2px 0 0 2px',
8
display: 'inline-flex',
9
};
10
11
const rowStyle = {
12
margin: '0 2px 2px 0',
13
background: 'gold',
14
};
15
16
const Grid = ({ cellStyle, columnsCount, rowsCount }) => {
17
const columns = Array(columnsCount);
18
for (let i = 0; i < columnsCount; ++i) {
19
const rows = Array(rowsCount);
20
for (let j = 0; j < rowsCount; ++j) {
21
rows[j] = <div key={j} style={{ cellStyle, rowStyle }}></div>;
22
}
23
columns[i] = <div key={i}>{rows}</div>;
24
}
25
return <div style={gridStyle}>{columns}</div>;
26
};
27
28
29
// Usage example:
30
31
const App = () => {
32
return <Grid cellStyle={{ width: '25px', height: '25px' }} columnsCount={5} rowsCount={5} />;
33
};
34
35
const root = document.querySelector('#root');
36
ReactDOM.render(<App />, root );