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 https://reactjs.org/. 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://www.jeejava.com/tic-tac-toe-game-using-java/

Prerequisites

Knowledge of HTML and JavaScript

Creating React application

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

Implementation of the game

Now we will see step by step how to implement tic-tac-toe game using React JS or React framework.

Now delete everything from the directory <drive/folder>/tic-tac-toe/src but do not delete src directory.

Create a functions.js file under src directory with below contents

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 we have used “export” before function because we want to use those functions into other modules or React Components.

In the above js file we 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 content

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;

We have imported required modules or components. We have initialized squares through constructor. We are also initially marked the X’s move as true. Please find more about state here https://reactjs.org/docs/faq-state.html. Then we call the renderSquare(i) method to render the square button for each value from 0 to 8. We also used onClick() method to handle what happens when a square is clicked. We 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 we render https://reactjs.org/docs/render-props.html what we want to display on the browser.

Finally we use “export default Board;” for importing Board into other components.

Now create below Game.js file under src directory with below contents

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 we 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 we have called <Game /> component and writing the output of the Game to the div id marked as “root”.

Open the file <drive/folder>/tic-tac-toe/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 you wish. If you want to implement the game in Java then you can visit the URL https://www.jeejava.com/tic-tac-toe-game-using-java/

You should see the output in the browser similar to the below image

tic tac toe

Thanks for reading.

Soumitra Roy Sarkar

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials Twitter Facebook  Google Plus Linkedin

Leave a Reply

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