Blog>
Snippets

Implementing a Dynamic Grid Layout with CSS Grid and Next.js 14

Show how to use CSS Grid in combination with React state to create a responsive and dynamic grid layout that can be customized based on user interaction or data.
import React, { useState } from 'react';
import styles from './Grid.module.css'; // import the CSS module

const DynamicGrid = () => {
  // State to hold the number of columns
  const [numColumns, setNumColumns] = useState(3);

  // Sample data to populate the grid
  const items = new Array(12).fill(null).map((_, index) => `Item ${index + 1}`);

  return (
    <div>
      <button onClick={() => setNumColumns(numColumns + 1)}>Add Column</button>
      <button onClick={() => setNumColumns(Math.max(numColumns - 1, 1))}>Remove Column</button>
      <div className={styles.grid} style={{ gridTemplateColumns: `repeat(${numColumns}, 1fr)` }}>
        {items.map((item, index) => (
          <div key={index} className={styles.gridItem}>
            {item}
          </div>
        ))}
      </div>
    </div>
  );
};

export default DynamicGrid;
In this piece of code, we create a React functional component named DynamicGrid that utilizes CSS Grid with dynamic behavior. We import React's useState to keep track of the number of columns in the grid. The state is initialized with 3 columns. We handle user interaction by providing buttons to add and remove columns. The CSS properties for grid layout are dynamically updated using inline styles that include the number of columns based on state. This component would be styled by accompanying CSS module styles with .grid and .gridItem classes for the grid container and grid items respectively.
/* Grid.module.css */
.grid {
  display: grid;
  gap: 10px; /* Space between grid items */
}

.gridItem {
  background-color: #f0f0f0; /* Background color for grid items */
  border: 1px solid #ddd; /* Border for grid items */
  padding: 20px; /* Padding inside grid items */
  text-align: center; /* Centering text inside grid items */
}
Here we have a CSS module that defines the styles for our grid layout. The .grid class sets up the grid container with grid display and a gap between items. The .gridItem class styles individual grid items with background color, border, padding, and center-aligned text. Import this CSS module in the React component to apply these styles to the grid layout.