Start learning free

LESSON 159 OF 161 · FRONTEND: INTERVIEW QUESTIONS

Tic-Tac-Toe

Practice

A classic machine-coding question: build tic-tac-toe in React. The board is one piece of state, squares: an array of nine values, null for an empty square, or "X" or "O". Everything else, whose turn it is, the winner and a draw, is worked out from the board on every render instead of being kept in more state.

A value worked out from state is just a variable at the top of the component. A shopping list, for example, doesn't need a second state to say how much is left:

const left = items.filter((item) => !item.bought).length;
const label = left === 0 ? "All done" : left + " to buy";

Each time items changes, React renders again and label is right again. The board works the same way. Its buttons have a title, "Square 1" to "Square 9", which names a square while it is empty; once it holds a mark, the check names it by its text, X or O. A win is three equal marks on one of the eight lines in LINES, and after a win the board takes no more clicks until Restart.

The check plays two games. What it must print (shortened):

> open the page
    heading 1: Tic-Tac-Toe
    text: Next: X
    group "Board": button: Square 1 … button: Square 9
    button: Restart
> click "Square 1"   - text: Next: X   + text: Next: O   - button: Square 1   + button: X
> click "Square 4"   - text: Next: O   + text: Next: X   - button: Square 4   + button: O
> click "Square 2"   … + button: X
> click "Square 5"   … + button: O
> click "X"          screen: no change
> click "Square 3"   - text: Next: X   + text: X wins   - button: Square 3   + button: X
> click "Square 9"   screen: no change
> click "Restart"    - text: X wins   + text: Next: X   (Squares 1 to 5 are empty again)
… a second game fills all nine squares with no line of three …
> click "Square 8"   - text: Next: X   + text: Draw   - button: Square 8   + button: X

Your task: in src/App.jsx, work out whose turn it is and show Next: X or Next: O, put the right mark on a clicked square, find a winner with findWinner and show X wins or Draw, ignore clicks on taken squares and after a win, and add a Restart button.


Assignment
Follow the Coding Tutorial to make the board take turns, show the status, find a winner and a draw, stop the game after a win and start a new one with Restart.


Hint
Only play and the Restart button call setSquares. xIsNext, winner and status are plain variables worked out from squares before the return.


STEP 1 OF 11
    Ctrl + Enter to check