“FE Interview — Building a Tic Tac Toe Game with React and TypeScript”

SHUBHAM GAUTAM
4 min readFeb 1, 2023

--

Photo by Solstice Hannan on Unsplash

Building tic tac toe game was one of the favourite interview question for FE interviewer and why no it be as it touch all aspect of FED. So, let’s build one :)

Tic Tac Toe is a classic two-player game that is easy to play and can be implemented with a few lines of code. In this tutorial, we will be using React and TypeScript to build a Tic Tac Toe game. The game will be built using functional components, hooks, and TypeScript interfaces. By the end of this tutorial, you will have a fully functional Tic Tac Toe game that can be played in the browser.

Step 1: Setting up the project To set up the project, you will need to have Node.js installed on your machine. If you don’t have it installed, you can download it from the official Node.js website.

Next, create a new directory for your project and open a terminal in that directory. Run the following command to create a new React project:

npx create-react-app tic-tac-toe --template typescript

Step 2: Creating the game board Next, we will create the game board. Create a new file called Board.tsx in the src directory and add the following code:

import React, { useState } from 'react';

interface SquareProps {
value: string;
onClick: () => void;
}

const Square: React.FC<SquareProps> = ({ value, onClick }) => (
<button className="square" onClick={onClick}>
{value}
</button>
);

interface BoardProps {
squares: string[];
onClick: (i: number) => void;
}

const Board: React.FC<BoardProps> = ({ squares, onClick }) => {
const renderSquare = (i: number) => <Square value={squares[i]} onClick={() => onClick(i)} />;

return (
<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;

Step 3: Creating the game component Next, we will create the game component. Create a new file called Game.tsx in the src directory and add the following code:

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

const Game: React.FC = () => {
const [history, setHistory] = useState([Array(9).fill(null)]);
const [stepNumber, setStepNumber] = useState(0);
const [xIsNext, setXIsNext] = useState(true);

const current = history[stepNumber];
const winner = calculateWinner(current);

const handleClick = (i: number) => {
const newHistory = history.slice(0, stepNumber + 1);
const current = newHistory[newHistory.length - 1];
const squares = current.slice();
if (winner || squares[i]) {
return;
}

squares[i] = xIsNext ? 'X' : 'O';
setHistory([...newHistory, squares]);
setStepNumber(newHistory.length);
setXIsNext(!xIsNext);
};
const jumpTo = (step: number) => {
setStepNumber(step);
setXIsNext(step % 2 === 0);
};

const moves = history.map((_step, move) => {
const desc = move ? Go to move #${ move }: 'Go to game start';
return (
<li key={move}>
<button onClick={() => jumpTo(move)}>{desc}</button>
</li>
);
});

let status;
if (winner) {
status = Winner: ${ winner };
} else if (stepNumber === 9) {
status = 'Draw';
} else {
status = Next player: ${ xIsNext ? 'X' : 'O' };
}

return (
<div className="game">
<div className="game-board">
<Board squares={current} onClick={handleClick} />
</div>
<div className="game-info">
<div>{status}</div>
<ol>{moves}</ol>
</div>
</div>
);
};

const calculateWinner = (squares: string[]) => {
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 (const line of lines) {
const [a, b, c] = line;
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
return squares[a];
}
}
return null;
};

export default Game;

Step 4: Updating the App component Finally, we will update the App component to display the game. Open the `App.tsx` file in the `src` directory and replace the contents with the following code:

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

const App: React.FC = () => {
return (
<div className="App">
<Game />
</div>
);
};

export default App;

Step 5: Adding styles Add the following styles to the index.css file in the src directory:

.square {
background: #fff;
border: 1px solid #999;
float: left;
font-size: 24px;
font-weight:bold;
line-height: 34px;
height: 34px;
margin-right: -1px;
margin-top: -1px;
padding: 0;
text-align: center;
width: 34px;
}

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

.status {
margin-bottom: 10px;
}

.game {
display: flex;
flex-direction: row;
}

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

And that’s it! You’ve successfully created a Tic Tac Toe game with React and TypeScript. If you run the project with `npm start`, you should be able to play the game in your browser.

I hope this tutorial was helpful and gave you a good understanding of how to build a Tic Tac Toe game with React and TypeScript. If you have any questions or comments, feel free to reach out!

Happy Coding !!!

--

--

No responses yet