I try to learn ReactJS. I already follow tutorial from https://react.dev/learn/tutorial-tic-tac-toe. But had a hard time to solve the 2nd Challenge of the tutorial.
Picture of the Problem
We have main board of the tic-tac-toe which generated manually. It contains of 9 Square Components
And in 2nd Challange, I want to generate the board automatically. , generate 9 Square Components
I already using Array Map and The Board is successfully generated. **The expected behavior is : ** when I click one of the Square for the first time, the clicked square user interface is changed into ‘X’. It works when the board generated manually.
But when I use Array.Map to generate the Square Components, When I click one of the Square for the first time, All the Square that automatically generated changed into ‘X’.
Meanwhile, the manual generated Square still working like usual, because each of it hold it’s own state.
Here is the code for generating Square Automatically:
function generateSquare(dimension) {
let dimensionTranslate = [...Array(dimension).keys()];
return(
dimensionTranslate.map((row) => {
return(<div className="board-row">
{
dimensionTranslate.map((column) => {
let squareIndex = (dimension*row)-row + column;
return <Square key={squareIndex} value={squares[{ squareIndex }]} onSquareClick={() => handleClick({ squareIndex })} />
})
}
</div>
)
})
)
}
the square Index generating correct value : 0,1,2,3,4,5,6,7,8.
Below code consist of generating square manually:
<>
<div className="status">{status}</div>
<p>Following board is generated automatically</p>
{generateSquare(3)}
<p>Following board is generated manually</p>
<div className="board-row">
<Square value={squares[0]} onSquareClick={() => handleClick(0)} />
<Square value={squares[1]} onSquareClick={() => handleClick(1)} />
<Square value={squares[2]} onSquareClick={() => handleClick(2)} />
</div>
<div className="board-row">
<Square value={squares[3]} onSquareClick={() => handleClick(3)} />
<Square value={squares[4]} onSquareClick={() => handleClick(4)} />
<Square value={squares[5]} onSquareClick={() => handleClick(5)} />
</div>
<div className="board-row">
<Square value={squares[6]} onSquareClick={() => handleClick(6)} />
<Square value={squares[7]} onSquareClick={() => handleClick(7)} />
<Square value={squares[8]} onSquareClick={() => handleClick(8)} />
</div>
</>
I already working on this for almost 2 days, but I couldn’t found the root cause of the issue.
I already tried following things :
- Change the map into for loop (Doesn’t work)
- Reduce the looping of .Map Function, currently it has 2 loop for making new row in user interface (Doesn’t work, the behavior still the same.)
- Make sure the Squareindex is correctly assigned (It is assigned correctly, Doesn’t work, the behavior still the same.)
- Put the the Mapping result in Const variable instead of a function with a return (Doesn’t work, the behavior still the same.)