I am quite new in React and trying to understand the code in Tic-tac-toe.
import { useState } from "react";
//side function Square (will have value and onClick)
function Square({ value, onSquareClick }) {
return (
<button className="square" onClick={onSquareClick}>
{value}
</button>
);
}
//function to find winner
function calculateWinner(squares) {
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
for (let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
if (squares[a] === squares[b] && squares[a] === squares[c]) {
return squares[a];
}
}
return null;
}
export default function Board() {
//1st, set 9 array for squares
const [squares, setSquares] = useState(Array(9).fill(null));
const [xIsNext, setXIsNext] = useState(true);
function handleClick(i) {
if (winner || squares[i]) {
return;
}
const nextSquares = squares.slice();
if (xIsNext) {
nextSquares[i] = "X";
} else {
nextSquares[i] = "O";
}
setXIsNext(!xIsNext);
setSquares(nextSquares);
}
const winner = calculateWinner(squares);
let status;
if (winner) {
status = "Winner is: " + winner;
} else {
status = "There is no winner";
}
return (
<>
<div className="status">{status}</div>
<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>
</>
);
}
In function Board, the handleClick function has this part: if (winner || squares[i]){return}....to make function return early with either condition. If winner exists, there will be NO MORE ACTION ALLOWED, or if you click on a square already filled, YOU CAN STILL MOVE ON AND FILL OTHER SQUARES.
So why do these two conditions respond differently while being handled with the same early return???? Hope that makes sense. Thank you so much everyone!
The difference is that
winnerhas a value that does not depend oni: if it is true, it will be true no matter where you click. But the value ofsquares[i]depends oni: it might be truthy (i.e. occupied) for one value ofi, and falsy (i.e. free) for another.Either way the early return only concerns the single click that is being handled.
In the case the game has a winner, the user can still click multiple squares, but it is clear that the click handler will in all these cases take the quick exit, as in all these cases
winneris true.