Select items in user generated multidimensional array, whole column gets selected

Im building an app in which the user can input the height and width and generate a grid with those dimensions. Then when clicking in individual cells they can toggle them on or off. Im using a multidimensional array to display the individual state of each cell.

When clicking each cell, the coordinates get passed to an updater method that updates the multidimensional array state. The problem I’m encountering is that when clicking one item, the whole column gets toggled.

When clicking coordinates column 0 and row 0 in a 3×3 multidimensional array

Expected new updated array

[true, false, false],
[false, false, false],
[false, false, false]

Current Output:

[true, false, false],
[true, false, false],
[true, false, false]

I’ve checked if the correct coordinates are passed and they are correct. What seems to do the trick is only if I hard code a multidimensional array. I believe the issue happens when I generate a grid with the input coordinates.

import { useState } from 'react';
import './style.css';

import Grid from '../Grid';
import InputView from '../InputView';
import Navigation from '../Navigation';

const App = () => {
  const [inputView, setInputView] = useState({ visible: true, rebuildingGrid: false });
  const [gridSize, setGridSize] = useState({ width: 0, height: 0 });
  const [prevGridSize, setPrevGridSize] = useState(undefined);
  const [gridMatrix, setGridMatrix] = useState(undefined);

  const generateGrid = (size) => {
    var grid = [];
    var row = [];
    for(let i=0; i<size.width; i++) row.push(false);
    for(let j=0; j<size.height; j++) grid.push(row); 

    // works hard coded
    // var test = [
    //   [false, false, false],
    //   [false, false, false],
    //   [false, false, false],
    // ];
    //  setGridMatrix(test);

  const inputNewGrid = () => {
    setInputView({ visible: true, rebuildingGrid: true });

  const toggleCell = (coords) => {
    var { row, col } = coords;
    var newGridMatrix = [...gridMatrix];
    newGridMatrix[row][col] = newGridMatrix[row][col] === false ? true : false;

  return (
      <div onClick={() => console.log(gridMatrix)}>
          LOG MATRIX
      { inputView.visible ? 
          generateGrid={() => generateGrid(gridSize)}
          <Navigation inputNewGrid={inputNewGrid} />
          <Grid gridSize={gridSize} gridMatrix={gridMatrix} toggleCell={toggleCell} />

export default App;

44 thoughts on “Select items in user generated multidimensional array, whole column gets selected”

Leave a Comment