logo

Education

Mastering Tic Tac Toe Game in React: A Comprehensive Guide

Authore Name
Rakesh Purohit

Developer Advocate

Last updated on Sep 15, 2023

Have you ever wanted to build a tic tac toe game using React? If so, you're in the right place. In this blog post, we'll walk through the process of creating an interactive tic tac toe game in React from scratch. This guide is perfect for beginners who are just getting started with React and web development.

Why Build a Tic Tac Toe Game?

Building a tic tac toe game is a great way to learn and practice your React skills. It's a simple game that everyone knows how to play, but it involves enough logic and interactivity to make it a challenging and rewarding project for a beginner. Plus, it's a lot of fun!

Setting Up Your Environment

Before we start coding, we need to set up our development environment. First, you need to have Node.js and npm installed on your computer. If you don't have them yet, you can download them from the official Node.js website.

Once you have Node.js and npm installed, you can create a new React app using the Create React App command-line tool. Just open your terminal, navigate to the folder where you want to create your app, and run the following command:

1 // Your JavaScript code with proper indentation here 2

This command will create a new folder named "tic-tac-toe" with a basic React app inside it. Navigate into this folder using the command cd tic-tac-toe, and then start the app by running npm start. You should see your new React app running in your browser.

Creating the Board Component

Our tic tac toe game will consist of two main components: the Board component and the Square component. The Board component will represent the entire game board, and the Square component will represent a single cell on the board.

Let's start by creating the Board component. In your "src" folder, create a new file named "Board.js". In this file, import React and create a new function component named "Board". For now, this component will just return a div with the text "Board".

1 import React from 'react'; 2 3 function Board() { 4 return ( 5 <div> 6 Board 7 </div> 8 ); 9 } 10 11 export default Board; 12

Creating the Square Component

Next, let's create the Square component. In your "src" folder, create a new file named "Square.js". In this file, import React and create a new function component named "Square". This component will return a button that represents a single cell on the board.

1 import React from 'react'; 2 3 function Square() { 4 return ( 5 <button className="square"> 6 {/* TODO */} 7 </button> 8 ); 9 } 10 11 export default Square; 12

We'll add more functionality to this component later. For now, let's move on to the CSS.

Styling the Game

Our game needs some styling to make it look like a real tic tac toe board. In your "src" folder, create a new CSS file named "index.css" and add the following code:

1 .board { 2 display: grid; 3 grid-template-columns: repeat(3, 1fr); 4 gap: 10px; 5 } 6 7 .square { 8 width: 60px; 9 height: 60px; 10 background-color: #fff; 11 border: 1px solid #000; 12 font-size: 24px; 13 line-height: 60px; 14 text-align: center; 15 } 16

This CSS code styles the board as a grid with three columns, and styles each square as a 60x60 pixel button with a border and centered text.

Adding Interactivity

Now that we have our components and styles set up, let's add some interactivity to our game. We'll start by adding state to our Board component. State is a feature of React that allows components to have their own mutable data that can change over time.

In the Board component, import the useState hook from React at the top of the file. Then, inside the Board function, declare a new state variable named "squares" and initialize it with an array of nine null values. This array represents the state of the game board, with each element corresponding to a square on the board.

1 import React, { useState } from 'react'; 2 3 function Board() { 4 const [squares, setSquares] = useState(Array(9).fill(null)); 5 // ... 6 } 7 8 export default Board; 9

Next, let's modify the Square component to display the value of its corresponding square on the board. To do this, pass the value as a prop from the Board component to the Square component, and then display this prop inside the button in the Square component.

1 import React, { useState } from 'react'; 2 3 function Board() { 4 // ... 5 return ( 6 <div> 7 {squares.map((value, index) => ( 8 <Square key={index} value={value} /> 9 ))} 10 </div> 11 ); 12 } 13 14 function Square({ value }) { 15 return ( 16 <button className="square"> 17 {value} 18 </button> 19 ); 20 } 21 22 export default Board; 23

Now, when you click on a square, it should display an "X" or an "O" depending on the current player. But we're not done yet. We still need to add logic to determine the winner of the game.

Determining the Winner

To determine the winner of the game, we need to check if there are any winning combinations on the board. A winning combination is a row, column, or diagonal where all three squares have the same value.

In the Board component, create a new function named "calculateWinner" that takes the squares array as a parameter and returns the winner of the game, or null if there is no winner yet. This function should check all possible winning combinations and return the value of the winning squares if there is a winner.

1 import React, { useState } from 'react'; 2 3 function Board() { 4 // ... 5 function calculateWinner(squares) { 6 const lines = [ 7 [0, 1, 2], 8 [3, 4, 5], 9 [6, 7, 8], 10 [0, 3, 6], 11 [1, 4, 7], 12 [2, 5, 8], 13 [0, 4, 8], 14 [2, 4, 6], 15 ]; 16 for (let i = 0; i < lines.length; i++) { 17 const [a, b, c] = lines[i]; 18 if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) { 19 return squares[a]; 20 } 21 } 22 return null; 23 } 24 // ... 25 } 26 27 export default Board; 28

Now, you can use this function in the Board component to determine the winner of the game. If there is a winner, display a message at the top of the board announcing the winner. If there is no winner yet, display a message indicating whose turn it is.

1 import React, { useState } from 'react'; 2 3 function Board() { 4 // ... 5 const winner = calculateWinner(squares); 6 let status; 7 if (winner) { 8 status = 'Winner: ' + winner; 9 } else { 10 status = 'Next player: ' + (xIsNext ? 'X' : 'O'); 11 } 12 return ( 13 <div> 14 <div>{status}</div> 15 {/* ... */} 16 </div> 17 ); 18 } 19 20 export default Board; 21

Wrapping Up

Congratulations! You've just built a fully functional tic tac toe game with React. This project is a great introduction to React and web development, and it's a fun way to practice your skills.

If you want to take this project further, there are many ways you could enhance it. For example, you could add a feature to let players choose their own symbols, or a feature to let players play against the computer. The possibilities are endless!

As a software engineer, it's important to constantly learn and practice new skills. Building projects like this tic tac toe game is a great way to do that. I hope you found this guide helpful and that it inspired you to create your own projects.

Remember, the key to becoming a great developer is practice. So keep coding, keep learning, and most importantly, have fun!

If you want to see the full code for this project, you can find it on my GitHub page. If you have any questions or comments, feel free to leave them below. I'd love to hear from you!

And before I wrap up, I want to introduce you to a tool that has been a game-changer for me as a React developer. It's called WiseGPT. It's a promptless Generative AI for React developers that write code in your style without context limit. It also provides API integration by accepting Postman collection and also supports extending UI in the VSCode itself. It's like having a coding assistant that understands your coding style and helps you write better code faster. Check it out, it might just change the way you code!

Happy coding!

Short on time? Speed things up with DhiWise!!

Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!

You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.

Sign up to DhiWise for free

Read More