Build a Tic-Tac-Toe Game using React

We will learn how to build a tic-tac-toe game using react. A project like this gives you the best understanding of core concepts. With source code
tic tac toe, tic tac toe react, tic tac toe using react

How to build a tic-tac-toe game using react

Tic-tac-toe is the most popular game on the internet. Most of us very well know this game. It gives us lots of fun to play this game. And we can also play this game with friends. This game is available offline and online. It is best to pass the time.

In this article, we will learn how to build a tic-tac-toe game using react. As we know, to improve skills we should build projects. A project like this gives you the best understanding of core concepts. To create this project basic knowledge of react js is required. You should be aware of some react js core concepts such as react hook, props, ES6 features, etc.

I also provide react source code for you or you can see the full code on the GitHub repository.

Preview      GitHub

The logic of the tic-tac-toe game

This tic-tac-toe game contains nine boxes in a 3×3 box. And a heading that displays turns. This heading tells which player should play. Two players can play this game. The player who has the first move is ×. And the player who has the second move is ○. Players will move one by one. The player who fills boxes vertically, diagonally, and horizontally wins. If the match draws reload the window to restart it. This game is easy and has basic logic. It does not take too hard to understand it. 


Now let's start our project.

Projects You may also like:-

Installation

This project is created using vite, react, and tailwindcss. So, to start with it install react using vite, and don't forget about tailwindcss. You can also install react using react webpack. Vite is used to increasing the speed of the app. If you don't want vite for your project you can skip it. 

Need to learn how to install it. Check out the tutorial 👇🏼👇🏼👇🏼
We successfully install react and tailwind CSS. It's time to start our project.

Folder structure

It doesn't contain a complex structure. If you are familiar with react you can understand it easily.
This app contains only two files Boxes.jsx and App.jsx

  • App.jsx contains the logic of the tic-tac-toe game and it is the main file of the app.
  • Boxes.jsx has the code of the box which calls in the main file.
Let's add code to the react app.

Adding code to the App.jsx file

Copy the source code below and paste it into the App.jsx file. We will understand it later.

Source code of App.jsx file

import React from "react";
import { useState } from "react";
import Boxes from "./Boxes";

const GameScreen = () => {
  const [state, setState] = useState(Array(9).fill(null));
  const [isXTurn, setIsXTurn] = useState(true);

  const checkWinner = () => {
    const winnerLogic = [
      [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 logic of winnerLogic) {
      const [a, b, c] = logic;
      // console.log(logic);

      if (state[a] !== null && state[a] === state[b] && state[a] === state[c]) {
        return state[a];
      }
    }

    return false;
  };

  const isWinner = checkWinner();
  // console.log(isWinner);
  const handleEvent = (index) => {
    if (state[index] !== null) {
      return;
    }
    const copyState = [...state];

    copyState[index] = isXTurn ? "x" : "o";
    setState(copyState);
    setIsXTurn(!isXTurn);
  };
  console.log(isWinner);
  return (
    <div className="w-screen max-w-7xl min-h-screen flex justify-center flex-col items-center select-none">
      <h1 className="text-[#ff9a9e] font-bold text-2xl mb-5 ">
        {isXTurn ? "X" : "O"}'s Turn!
      </h1>
      <div className=" w-60 h-60 sm:w-96 sm:h-96 bg-gradient-to-br from-[#ff9a9e] to-[#ffaa93] grid grid-cols-3 grid-rows-3 gap-1 overflow-hidden place-items-stretch relative rounded-lg">
        {isWinner ? (
          <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2  flex justify-center items-center flex-col text-center ">
            <h1 className="text-white font-bold text-4xl sm:text-5xl">{`${isWinner} won!`}</h1>

            <button
              className="w-fit h-fit p-2 bg-white rounded-md mt-3 font-semibold text-[#f1a894]"
              onClick={() => {
                setState(Array(9).fill(null));
              }}
            >
              Play Again
            </button>
          </div>
        ) : (
          <>
            <Boxes value={state[0]} onClick={() => handleEvent(0)} />
            <Boxes value={state[1]} onClick={() => handleEvent(1)} />
            <Boxes value={state[2]} onClick={() => handleEvent(2)} />
            <Boxes value={state[3]} onClick={() => handleEvent(3)} />
            <Boxes value={state[4]} onClick={() => handleEvent(4)} />
            <Boxes value={state[5]} onClick={() => handleEvent(5)} />
            <Boxes value={state[6]} onClick={() => handleEvent(6)} />
            <Boxes value={state[7]} onClick={() => handleEvent(7)} />
            <Boxes value={state[8]} onClick={() => handleEvent(8)} />
          </>
        )}
      </div>
    </div>
  );
};

export default GameScreen;
 

Understanding the code

The jsx section of this tic-tac-toe project has three main elements heading, game container, and winner screen.

Here heading displays which player should move. It uses a state variable named isXTrurn. If isXTrurn is true it displays, it is an "X" player turn or if  isXTrurn is false it displays, it is an "O" turn.

The game container contains boxes that come from the Boxes.jsx file. We call Boxes components nine times that make nine boxes in the game container. In every box, two props are passed. First is a value (X or O) and a function named "handleEvent". This function accepts the index value of the clicked box and passes an array into the state variable named "state". It also changes the turn of the player. Basically, this function is responsible for filling the boxes with "X" and "O".

The winner screen displays when any one player wins the game. The function checkWinner is used here to display the winner screen. If any one player wins the game this function returns the player's name or if the match is drawn then it returns false. If the function returns the player name then the winner displays on the winner screen. 

Let's see how the checkWinner function works. This function has an array that contains all of the patterns of game winnings. Then it checks the winner and returns the winner's name if any one player wins.

It is time to add the code to the boxes.

Adding code to the Boxes.jsx file

Copy the react source code given below and paste it into the Boxes.jsx file.
const Boxes = (props) => {
  return (
    <>
      <div
        onClick={props.onClick}
        className=" bg-white grid place-items-center text-5xl font-semibold text-[#ff9a9e]"
      >
        {props.value}
      </div>
    </>
  );
};

export default Boxes; 

Understanding the source code

The component in this file has the code of the box which calls in the game container. This component accepts props that come from the main file. 

Finally, all work is done. Now enjoy this tic-tac-toe game on the browser. 

Conclusion

Well, this is pretty tough for a beginner. But once you try it, it becomes easy. This project can clear your basic concepts of react js. You can also add it to your portfolio. It definitely increases your impression.

This tic-tac-toe game also improves your logic-building and coding skills. There is a lot of fun in this project. And you can also play this game with your friends. 

I'm sure you learned something from this article. If yes, level a comment. If not, tell us your problem and we definitely try to solve it. 

Thank you! 

About the Author

Code Armor makes Full Stack Development easy. We provide code projects with live examples and source code. We help you to increase your coding skills and problem-solving skills. We provide you with code projects in technologies like HTML, CSS, JavaS…

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.