7.POCE.2: React Tic Tac Toe


Begin with the base React repo.


Create a playable game of tic tac toe in React. Switch between players automatically. The game ends when all squares are filled.
The board should be represented in a state variable using useState.
Don't use components for this game. Code everything in the App component.

Creating the Board

When creating the click events for the board, use map with index and inline anonymous functions so that a callback function is able to access the position of a specific element on the board (e.g, board[0][2]).

map with index

const numbers = [4, 6, 8, 9];
const doubled =, index) => {
console.log(num, index);
return num * 2;

map with inline callback

Note that on line 18 we specify a click event callback. When creating the tic tac toe game grid, use similar syntax so that we are able to access the the position of the square that was clicked. In the context of a tic tac toe board data structure, index would represent a row or column.
// a function that takes index as a parameter
const saySomething = (num, index) => {
console.log(`${num}: ${index}`);
// array to use with map
const numbers = [4, 6, 8, 9];
// create a button for each number
const buttons =, index) => {
console.log(num, index);
// when the button gets clicked, define an
// anon func. In the anon func, call saySomething
// index is passed into saySomething and we are able to access index in this way (lines 1-2)
return (
onClick={() => {
saySomething(num, index);

Board Data Structure

We'll use a nested array, like the one shown below, to represent the board. Replace each blank space ( ' ' ) with an 'X' or an 'O' by updating state, and thereby updating the DOM, as the game progresses.

Nested Maps

In order to iterate over this data structure a nested map will be needed to build the elements. Run the example code given below to see how this works. Note that CSS needs to be added to give it the appearance of a tic-tac-toe board.
// array to use with map
const numbers = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
// this line maps the 3 arrays that are in numbers, each row is one of those arrays
// rowIndex is the index number of each row (e.g, numbers[0])
// we use rowIndex here to keep track of / be able to access the row that we want
const rows =, rowIndex) => {
// this line takes each individual row (array) and maps the elements that are inside that array
// here, similar to the code above, colIndex is the index of each element inside 1 row
const buttons =, colIndex) => (<button>{num}</button>));
return (<div>
// rows is an array of div *elements* that have 3 buttons inside.
console.log( rows );



Create a button to reset the game.

Game Over

See if the game is won when a click happens.

Dynamic Board Size

Create a dropdown that allows the user to select the size of the board.

More Comfortable

Create a computer player.

Reference solution

Click here to see the reference solution.