Skip to main content

Creating a Tic Tac Toe game in React

· 4 min read
Parth Maheta

Creating a Tic Tac Toe game in React is a great way to learn about React's state management and component communication. Below is a step-by-step guide to creating a simple Tic Tac Toe game in React:

Step 1: Setup a React App

Create a new React app using Create React App:

npx create-react-app tic-tac-toe
cd tic-tac-toe

Step 2: Create Components

Create three components: Square, Board, and Game.

Square Component (Square.js):

// Square.js
import React from 'react';

const Square = ({ value, onClick }) => {
return (
<button className="square" onClick={onClick}>
{value}
</button>
);
};

export default Square;

Board Component (Board.js):

// Board.js
import React, { useState } from 'react';
import Square from './Square';

const Board = () => {
const [squares, setSquares] = useState(Array(9).fill(null));
const [xIsNext, setXIsNext] = useState(true);

const handleClick = (i) => {
const newSquares = squares.slice();
if (calculateWinner(newSquares) || newSquares[i]) {
return;
}
newSquares[i] = xIsNext ? 'X' : 'O';
setSquares(newSquares);
setXIsNext(!xIsNext);
};

const renderSquare = (i) => {
return <Square value={squares[i]} onClick={() => handleClick(i)} />;
};

const winner = calculateWinner(squares);
const status = winner
? `Winner: ${winner}`
: `Next player: ${xIsNext ? 'X' : 'O'}`;

return (
<div>
<div className="status">{status}</div>
<div className="board-row">
{renderSquare(0)}
{renderSquare(1)}
{renderSquare(2)}
</div>
<div className="board-row">
{renderSquare(3)}
{renderSquare(4)}
{renderSquare(5)}
</div>
<div className="board-row">
{renderSquare(6)}
{renderSquare(7)}
{renderSquare(8)}
</div>
</div>
);
};

export default Board;

Game Component (Game.js):

// Game.js
import React from 'react';
import Board from './Board';

const Game = () => {
return (
<div className="game">
<div className="game-board">
<Board />
</div>
<div className="game-info">
<div>{/* status */}</div>
<ol>{/* TODO: Display the move history */}</ol>
</div>
</div>
);
};

export default Game;

Step 3: Styling

Add some basic styling to your components for a better visual experience.

/* App.css */
.square {
background: #fff;
border: 1px solid #999;
fontSize: 24px;
fontWeight: bold;
cursor: pointer;
outline: none;
}

.board-row:after {
clear: both;
content: '';
display: table;
}

.status {
margin-bottom: 10px;
}

.game {
display: flex;
padding: 20px;
maxWidth: 600px;
margin: 50px auto;
font-family: Arial, sans-serif;
}

.game-info {
margin-left: 20px;
}

.game-board {
flex: 1;
}

Step 4: Helper Function

Define a helper function calculateWinner to determine the winner of the game.

// Add this helper function to Board.js
const 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[a] === squares[b] && squares[a] === squares[c]) {
return squares[a];
}
}
return null;
};

Step 5: Render the Game Component

Update index.js to render the Game component.

// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import Game from './Game';

ReactDOM.render(
<React.StrictMode>
<Game />
</React.StrictMode>,
document.getElementById('root')
);

Step 6: Run the App

Run your React app and open it in the browser:

npm start

Visit http://localhost:3000 to play your Tic Tac Toe game!

Explanation:

  • The Square component is a simple button that triggers the onClick event when clicked.
  • The Board component maintains the state of the game, handles user clicks, and determines the winner.
  • The Game component is the main container that includes the Board component.
  • The game logic is managed using React's state and the calculateWinner helper function.
  • Each square on the board is a Square component, and the board itself is composed of three rows of squares.
  • The winner is calculated using the helper function, and the game

status is displayed accordingly.

This simple React Tic Tac Toe game provides a foundation for understanding React state, component communication, and basic game development concepts. Feel free to enhance and customize the game further based on your learning goals.