How to make the color of a div change permanently after it has been clicked in react.js

Viewed 105

This is the grid that I have

Once a square has been clicked, the color changes to red. - This is done using active class

I would like the change to the background color of the div tag to remain permanent after the square has been clicked.

Code

Board.js

          {board.map((row, rowIdx) => (
            <div key={rowIdx} className="row">
              {row.map((cell, cellIdx) => (
                <div key={cellIdx} className="cell"></div>
               ))}
            </div>
              ))}

Board.css

.row {
  height: 30px;
  margin: 10px;
  transition: transform 0.1s;
}

.cell:hover {
  transform: scale(1.4);
}

.cell {
  width: 30px;
  height: 30px;
  outline: 1px solid rgb(134, 154, 189);
  display: inline-block;
  background-color: seagreen;
  margin: 5px;
  transition: transform 0.2s;

}

.row :active {
  background-color: red;
}

.cell :active {              // Does not do anything
  background-color: blue;
}
2 Answers

Once another square is clicked, the previosly clicked one does not remain active, you can do this by adding another class with your desired style, and using state to track the squares that have been clicked.

const [boardIndeces, setBoardIndeces] = useState(initArray(board));

const initArray = arr => {
  let rows = [];
  for (let i = 0; i < arr.length; i++) {
    let row = [];
    const currBoard = arr[i];
    for (let z = 0; z < currBoard.length; z++) {
      row[z] = false;
    }
    rows[i] = row;
  }
  return rows;
};

const onCellClick = (rowIdx, cellIdx) => {
  if (!(boardIndeces[rowIdx] && boardIndeces[rowIdx][cellIdx])) {
    boardIndeces[rowIdx][cellIdx] = true;
    setBoardIndeces([...boardIndeces]);
  }
};

{
  board.map((row, rowIdx) => (
    <div key={rowIdx}>
      {row.map((cell, cellIdx) => (
        <div
          key={cellIdx}
          className={
            boardIndeces[rowIdx].includes(cellIdx)
              ? 'your_active_class'
              : 'your_inactive_class'
          }
          onClick={() => onCellClick(rowIdx, cellIdx)}
        ></div>
      ))}
    </div>
  ));
}

You can use a checkbox if you don't want to use React

HTML

<input type="checkbox" id="color" name="color">
<label id="color-div" for="color">
    <!-- the div you want to change color -->
</label>

CSS

#color {
    display: none
}

#color:checked + #color-div { /* + in CSS is the sibling combinator */
   background-color: #fffff /* your background color */
}

What you're basically doing is making an invisible checkbox and toggling it with the label, when it's toggled you do the changes to the CSS Remember the CSS combinators only work in elements after the HTML element it's being applied to

Related