Here is an excerpt which should show my problem. In my project I do something with the grid and now I want to reset it, but I dont know how it works because if I change the grid variable, the .map() function doesnt re render. I hope you understand my problem and you can help me.
That is my code:
JavaScript
x
28
28
1
export default function App() {
2
const getInitialGrid = () => {
3
const grid = [];
4
for (let row = 0; row < 20; row++) {
5
const currentRow = [];
6
for (let col = 0; col < 50; col++) {
7
currentRow.push([]);
8
}
9
grid.push(currentRow);
10
}
11
return grid;
12
};
13
const grid = getInitialGrid();
14
return (
15
<div className="App">
16
{grid.map(function (row, rowIdx) {
17
return (
18
<div className="grid-row" key={rowIdx}>
19
{row.map(function (node, colIdx) {
20
return <div className="node">hi</div>;
21
})}
22
</div>
23
);
24
})}
25
</div>
26
);
27
}
28
Thanks a lot!
Advertisement
Answer
You should use useState hook for that.
JavaScript
1
7
1
import React, { useState } from 'react';
2
3
export default function App() {
4
// App code
5
const [grid, setGrid] = useState(getInitialGrid());
6
// more App code
7
then if you want to assign a new value to the grid and cause a rerender you do it like this (inside your App component):
JavaScript
1
2
1
setGrid(yourNewGrid);
2