React tic tac toe handleClick

I’ve been working through the tutorial on Reactjs.org . I don’t understand why the handleClick method stops the app updating once a winner is declared but only ignores the click if the square is already filled. Here is the function:

  handleClick(i) {
    const squares = this.state.squares.slice();
    if (calculateWinner(squares) || squares[i]) {
      return;
    }
    squares[i] = this.state.xIsNext ? 'X' : 'O';
    this.setState({
      squares: squares,
      xIsNext: !this.state.xIsNext,
    });
  }

It’s not clear which part baffles you. If the square is set or the game has been won, there’s nothing left to be done by the function, so it exits prematurely. Say you wanted to add an annoying beep if a player clicked on a full square, you’d move the second check to an individual if block and first make the sound before again returning prematurely — not allowing rewriting the position.

What I don’t understand is why it still allows you to play if you click on a square that’s filled but stops play completely if a winner is declared, seeing as both checks exist in the same if statement.

Thanks, I do understand this part. I’ll try and rephrase again. How come when the function exits prematurely when the calculateWinner function returns something, no further clicks can be made, but when a player clicks on a square which is filled it exits (based on the same return statement) but allows further play once you click on an empty square.
In other words, why does the same return statement seem to yield slightly different results?

can you share the full code on maybe a codepen.io so I can see it

The reason you have two different results is because you are using a conditional statement meaning if the first statement is not true you move to the next step, but if you want to keep playing after the winner was announced then you need to loop though the condition of if.

Thanks, I think I understand now. Because once the calculateWinner function evaluates as true, it cannot go back to returning null, so the if statement will always return true, thus seeming to stop play.

1 Like