Joji
Joji

Reputation: 5646

How do I display a grid in React using CSS grid

I have a 2d array representing the columns (as opposed to rows):

const cols = [
  [1, 2, 3],
  [1, 2, 3],
  [1, 2, 3],
  [1, 2, 3],
  [1, 2, 3],
  [1, 2, 3],
  [1, 2, 3]
];

I am writing a React component to display a grid with this column data where each cell is a 20px x 20px square with margins.

export default function App() {
  return (
    <div className="App">
      <div className="board">
        {cols.map((col) => (
          <div className="column">
            {col.map((cell) => (
              <div className="cell">{cell}</div>
            ))}
          </div>
        ))}
      </div>
    </div>
  );
.App {
  font-family: sans-serif;
  text-align: center;
}

.cell {
  width: 20px;
  height: 20px;
  background-color: bisque;
}

.board {
  display: grid;
  grid-template-columns: repeat(7, 0fr);
  gap: 20px;
}

but now only the columns are separated by the gap, rows are still not separated.

Here is a demo.

I don't want to add margins to cell class directly as that will cause margins to the cells on the borders which is not what I want. I only want margins between them.

Upvotes: 1

Views: 921

Answers (1)

Amila Senadheera
Amila Senadheera

Reputation: 13245

Add the following properties to your column class:

.column {
  display: grid;
  gap: 20px;
}

const cols = [
  [1, 2, 3],
  [1, 2, 3],
  [1, 2, 3],
  [1, 2, 3],
  [1, 2, 3],
  [1, 2, 3],
  [1, 2, 3]
];

function App() {
  return (
    <div className="App">
      <div className="board">
        {cols.map((col, colIdx) => (
          <div className="column" key={colIdx}>
            {col.map((cell, cellIdx) => (
              <div className="cell" key={cellIdx}>{cell}</div>
            ))}
          </div>
        ))}
      </div>
    </div>
  );
}

ReactDOM.render(<App />, document.querySelector('.react'));
.App {
  font-family: sans-serif;
  text-align: center;
}

.cell {
  width: 20px;
  height: 20px;
  background-color: bisque;
}

.board {
  display: grid;
  grid-template-columns: repeat(7, 0fr);
  gap: 20px;
}

.column {
  display: grid;
  gap: 20px;
}
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

Upvotes: 1

Related Questions