Tic Tac Toe
MediumReact Components20 min6 tests
Build an interactive 3x3 Tic Tac Toe board where two players alternate placing X and O, with a live status line that announces whose turn it is and who has won.
Implement a classic Tic Tac Toe game as a single React component.
The board is a 3x3 grid of 9 cells, each rendered as a <button> with an accessible name of "Cell 1" through "Cell 9" (left-to-right, top-to-bottom). A cell's visible text is its current mark (X, O, or empty).
Rules:
Xalways moves first. Players then alternate: after anXmove it becomesO's turn, and vice versa.- Clicking an empty cell places the current player's mark there as the button's text.
- Clicking an occupied cell does nothing.
- A live status region (
role="status") shows"Next: X"or"Next: O"while the game is in progress. - When a player gets three of their marks in a row (any row, column, or either diagonal), the status changes to
"Winner: X"or"Winner: O", and all further clicks are ignored — the board is frozen.
Render a heading for the game and the status region in addition to the board.
Requirements
- Render a heading (role="heading") for the game.
- Render 9 cell buttons with accessible names "Cell 1".."Cell 9".
- Render a role="status" element showing "Next: X" initially (X moves first).
- Clicking an empty cell places the current player's mark (X then alternating O/X) as the button text and updates the status to the next player.
- Clicking an already-occupied cell is ignored (no change to mark or turn).
- When three matching marks align in any row, column, or diagonal, the status shows "Winner: X" or "Winner: O".
- After a win, all further cell clicks are ignored (board frozen).
Hints (4)
- Keep board state as an array of 9 strings ("" for empty). Derive the current player from how many marks are placed, or track it explicitly.
- Compute the winner by checking 8 lines (3 rows, 3 columns, 2 diagonals) for three equal non-empty marks.
- In the click handler, return early if the cell is non-empty or a winner already exists, so occupied and post-win clicks are no-ops.
- Use role="status" for the live text so it can be queried with getByRole('status').
Topics
- React
- React Components
Asked at
Razorpay · Zoho · Urban Company · Zerodha · Uber · Hotstar
