Categories
React Projects

Create a Tic Tac Toe Game with React and JavaScript

Spread the love

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a tic tac toe game with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app tic-tac-toe

with NPM to create our React project.

Create the Tic Tac Toe Game

To create the tic tac toe game, we write:

import React, { useMemo, useState } from "react";

export default function App() {
  const [board, setBoard] = useState([[], [], []]);

  const restart = () => {
    setBoard([[], [], []]);
  };

  const isWinner = (player) => {
    return (
      (board[0][0] === player &&
        board[0][1] === player &&
        board[0][2] === player) ||
      (board[1][0] === player &&
        board[1][1] === player &&
        board[1][2] === player) ||
      (board[2][0] === player &&
        board[2][1] === player &&
        board[2][2] === player) ||
      (board[0][0] === player &&
        board[1][0] === player &&
        board[2][0] === player) ||
      (board[0][1] === player &&
        board[1][1] === player &&
        board[2][1] === player) ||
      (board[0][2] === player &&
        board[1][2] === player &&
        board[2][2] === player) ||
      (board[0][0] === player &&
        board[1][1] === player &&
        board[2][2] === player) ||
      (board[0][2] === player &&
        board[1][1] === player &&
        board[2][0] === player)
    );
  };

  const xWins = useMemo(() => {
    return isWinner("x");
  }, [board, isWinner]);

  const oWins = useMemo(() => {
    return isWinner("o");
  }, [board, isWinner]);

  if (xWins || oWins) {
    if (xWins) {
      return (
        <>
          <div>x wins</div>
          <button onClick={restart}>restart</button>
        </>
      );
    }

    if (oWins) {
      return (
        <>
          <div>o wins</div>
          <button onClick={restart}>restart</button>
        </>
      );
    }
  } else {
    return (
      <div className="App">
        <form>
          {Array(3)
            .fill()
            .map((_, i) => {
              return (
                <div key={i}>
                  {Array(3)
                    .fill()
                    .map((_, j) => {
                      return (
                        <span key={j}>
                          <input
                            value={board[i][j] || ""}
                            onChange={(e) => {
                              const b = [...board];
                              b[i][j] = e.target.value;
                              setBoard(b);
                            }}
                            style={{ width: 20 }}
                          />
                        </span>
                      );
                    })}
                </div>
              );
            })}
        </form>
      </div>
    );
  }
}

We have the board state which holds the tic tac toe values.

The restart function calls setBoard to clear the board.

Then we have the isWinner function that checks if the player fills in the board in a way that the player wins.

We check each possible combination to see if the player wins, including horizontal, vertical, and diagonal combinations.

Then we define the xWins and oWins with useMemo with a callback that calls isWinner with the player string to see if the player wins.

We watch the board and isWinner variables for updates.

Then we check xWins and oWins .

In either case, we show who wins and the restart button.

Otherwise, we render the nested array into a grid of inputs.

Each input has the value set to the board[i][j] value.

Then to update the value when the user types it in, we have the onChange prop set to a function that makes a copy of the board and set it to b .

Then we set b[i][j] to e.target.value .

And then we call setBoard with b to update the board.

We set the input style to width 20px.

Conclusion

We can create a tic tac toe game with React and JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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