Reputation: 33
I'm trying to change the grid size on my Conway game of life app but when I click button to set new numCols/numRows only one of them is effected on the app. How do I affectively set new state so grid changes size as expected.
I have 2 buttons in the app, one to make grid smaller, one to make it bigger. onClick they Trigger function sizeHandler & sizeHandler2.
My guess is I need to set new state in a different method but I tried a few methods to no avail.
import React, { useState } from 'react'
import './App.css';
function App() {
const color = "#111"
const [numRows, setNumRows] = useState(20)
const [numCols, setNumCols] = useState(20)
const generateEmptyGrid = () => {
const rows = [];
for (let i = 0; i < numRows; i++) {
rows.push(Array.from(Array(numCols), () => 0))
}
return rows
}
const [grid, setGrid] = useState(() => {
return generateEmptyGrid();
})
const sizeHandler = () => {
setNumRows(40)
setNumCols(40)
}
const sizeHandler2 = () => {
setNumRows(20)
setNumCols(20)
}
// RENDER
return (
<div className="page">
<div className="title">
<h1>
Conway's Game Of Life
</h1>
<button onClick={sizeHandler}>
Size+
</button>
<button onClick={sizeHandler2}>
Size-
</button>
</div>
<div className="grid" style={{
display: 'grid',
gridTemplateColumns: `repeat(${numCols}, 20px)`
}}>
{grid.map((rows, i) =>
rows.map((col, j) =>
<div className="node"
key={`${i}-${j}`}
style={{
width: 20,
height: 20,
border: 'solid 1px grey',
backgroundColor: grid[i][j] ? color : undefined
}}
/>
))}
</div>
</div>
);
}
export default App;
Upvotes: 0
Views: 145
Reputation: 2682
What you are doing is you want a change of numRows
and numCols
to have a side effect. You actually almost said it yourself. React has a hook for that: useEffect
:
useEffect(() => {
setGrid(generateEmptyGrid())
}, [numRows, numCols]);
Upvotes: 1