Tic-tac-toe game using React JS

In this tutorial you will see how to build Tic-tac-toe (tic tac toe) game using React or React JS web framework. React is a declarative, efficient, and flexible JavaScript library for building user interfaces. You may read more about tic-tac-toe game at https://en.wikipedia.org/wiki/Tic-tac-toe. You may also read tic tac toe using Java here https://roytuts.com/tic-tac-toe-game-using-java/

Prerequisites

Knowledge of HTML and JavaScript

Please read the tutorial Create React JS Application before moving forward.

Implementation of the game

Now you will see the following steps on how to implement tic-tac-toe game using React JS or React framework.

I assume that you have already created react js application. The name of the project root directory is tic-tac-toe-game. Now delete everything from the directory tic-tac-toe-game/src but do not delete src directory.

Create a functions.js file under src directory with below code:

import React from 'react';

export function square(props) {
	return (
		<button className="square" onClick={props.onClick}>
			{props.value}
		</button>
	);
}

export function findWinner(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;
}

export function isAllSquareClicked(squares) {
	let count = 0;
	squares.forEach(function (item) {
		if (item !== null) {
			count++;
		}
	});
	if(count === 9) {
		return true;
	} else {
		return false;
	}
}

You see I have used export before each function I have defined because you need to use these functions into other modules or React Components.

In the above js file you have three functions – square(), findWinner() and isAllSquareClicked().

The first function renders the square button, the second function finds the winner and third function checks if all squares are clicked because if all squares are clicked but no one is winner then we need to display “Game drawn”.

The winner may be the one with vertical or horizontal or diagonal same entries.

Read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import to know about import statement.

Create below index.css file under src folder for adding some styles to the game.

body {
	font: 14px "Times New Roman", Times, serif;
	margin: 20px;
}

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

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

.square:focus {
	outline: none;
}

.status {
	margin: 10px;
}

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

Create Board.js file under src directory with below code:

import React from 'react';
import * as utils from './functions.js';
import './index.css';

class Board extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			squares: Array(9).fill(null),
			xIsNext: true,
		};
	}
	
	renderSquare(i) {
		return <utils.square value={this.state.squares[i]} onClick={() => this.handleClick(i)}/>;
	}
	
	handleClick(i) {
		const squares = this.state.squares.slice();
		if (utils.findWinner(squares) || squares[i]) {
			return;
		}
    
		if(utils.isAllSquareClicked(squares) === true) {
			return;
		}
		
		squares[i] = this.state.xIsNext ? 'X' : 'O';
		this.setState({
			squares: squares,
			xIsNext: !this.state.xIsNext
		});
	}

	render() {
		const winner = utils.findWinner(this.state.squares);
		const isFilled = utils.isAllSquareClicked(this.state.squares);
		let status;
		if (winner) {
			status = 'Winner: ' + winner;
		} else if(!winner && isFilled) {
			status = 'Game drawn';
		} else {
			status = 'Now ' + (this.state.xIsNext ? 'X' : 'O') + '\'s turn';
		}
    
		return (
			<div>
				<div className="status">{status}</div>
				<div className="board-row">
				  {this.renderSquare(0)}
				  {this.renderSquare(1)}
				  {this.renderSquare(2)}
				</div>
				<div className="board-row">
				  {this.renderSquare(3)}
				  {this.renderSquare(4)}
				  {this.renderSquare(5)}
				</div>
				<div className="board-row">
				  {this.renderSquare(6)}
				  {this.renderSquare(7)}
				  {this.renderSquare(8)}
				</div>
			</div>
		);
	}
}

export default Board;

I have imported required modules or components. I have initialized squares through constructor. I also initially marked the X’s move as true.

Then we call the renderSquare(i) method to render the square button for each value from 0 to 8. I also used onClick() method to handle what happens when a square is clicked. I have called handleClick(i) method to compute winner on each click on the square button and also we find whose move is next (X or O). Using render() method I render what I want to display on the user interface (browser).

Finally I used export default Board; for importing Board into other components.

Now create below Game.js file under src directory with below code:

import React from 'react';
import Board from './Board'
import './index.css';

class Game extends React.Component {
  render() {
    return (
      <div className="game">
          <Board />
      </div>
    );
  }
}

export default Game;

In this class I have used component <Board/> to display the board game.

Finally create index.js file under src directory to start up the application.

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

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

Here I have called <Game/> component and writing the output of the Game to the div id marked as root.

Open the file tic-tac-toe-game/src/public/index.html, you will find a div with “root” id. Update the title in this file as Game - tic tac toe.

Now you are done and you can play the game as well. If you want to implement the tic-tac-toe game in Java then you can visit the URL https://roytuts.com/tic-tac-toe-game-using-java/

You can hit the URL http://localhost:3000. You should see the output in the browser similar to the below image:

tic tac toe game using reactjs

Source Code

Download

Thanks for reading.

1 thought on “Tic-tac-toe game using React JS

Leave a Reply

Your email address will not be published. Required fields are marked *