I am trying to update a matrix of 20x20 values, each slot is binded to a div, once a div is clicked, its background color should change.
What is the best way of doing this, without having to set the whole matrix?
Also, why do some set methods don't work, since most of these are used in examples through the internet?
import { useState } from "react";
function App() {
const n = 20;
// define [20][20] array with default value on each slot as { color: "red" }
const [matrix, setMatrix] = useState(Array(n).fill(Array(n).fill({ color: "red" })))
let updateCell = (i, j) => {
console.log(i, j); // Works perfectly, returns i and j of the matrix slot binded to the clicked cell.
// const mat = matrix; mat[i][j].color = "blue"; // Doesnt work
// setMatrix((mat) => { mat[i][j].color = "blue"; return mat; }); // Doesnt work
// matrix[i][j].color = "blue"; setMatrix(matrix); // Doesnt work
// matrix[i][j].color = "blue"; setMatrix([...matrix]); // Changes ALL squares instead of the one clicked.
// const mat = Object.assign({}, matrix); setMatrix(mat); // TypeError: matrix.map is not a function
}
return (
<div className="container">
{/* Renders all squares fine! */}
{matrix.map((i, ipos) => {
console.log(matrix.length);
return (
<div key={ipos} className="d-flex flex-row wrap">
{i.map((j, jpos) => {
console.log(i.length);
return (
<div
style={{ backgroundColor: matrix[ipos][jpos].color, minWidth: "5%", minHeight: "50px", textAlign: "center", color: "white" }}
key={ipos + ", " + jpos}
onClick={() => { updateCell(ipos, jpos) }}
>
{ipos + ", " + jpos}
</div>
)
})}
</div>
)
})}
</div>
)
}
export default App;
Best regards, and thank you.