Facebook Pixel

Grid Lights

React.js
medium
mins

Requirements:

You are tasked with simulating a grid of lights that can be toggled on or off. The grid is initially in the "off" state. Each light in the grid can be toggled by clicking on it. When a light is toggled, the light itself and all adjacent lights (horizontally and vertically) also toggle their states.

The grid is composed of n x n cells, and each cell represents a light that can either be on (1) or off (0). The grid starts with all lights in the off state.

You need to implement a solution that allows toggling the lights and keeps track of the current state of the grid. Make sure to use inline css.

Component Structure:

  • A single functional component named GridLights.
  • Grid size n should be passed as a prop (default to 5 if not provided).

State Management:

  • Use useState to manage the grid state.
  • Maintain a 2D array to represent the current on/off state of each light.

UI Behavior:

  • Display the grid using simple square cells.
  • A light in the "on" state should be visually different and have background color "gold".
  • A light in the "off" state should have a neutral background color "lightgray".
  • Clicking on a cell toggles the state of:
    • The clicked cell
    • The top neighbor (if it exists)
    • The bottom neighbor (if it exists)
    • The left neighbor (if it exists)
    • The right neighbor (if it exists)
  • Each cell should have role="cell"

User Interaction:

  • Clicking on a cell updates the grid immediately.
  • UI should be responsive and update in real-time based on state.

Reference UI

gridLights

Preview what you need to build

Solve Similar questions 🔥

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.