Tic-Tac-Toe, the traditional paper-and-pencil sport, has been a favourite pastime for generations. Because of fashionable internet applied sciences and frameworks like React, making a digital model of this timeless sport has by no means been simpler. On this article, we’ll stroll by way of the steps of constructing a easy Tic-Tac-Toe sport utilizing React, offering each the code and the styling essential to convey the sport to life.



Preliminary Mission Setup

Create a brand new undertaking utilizing create-react-app

npx create-react-app your-component-app
Enter fullscreen mode

Exit fullscreen mode



Step 1: Import React and useState Hook

import React, { useState } from "react";
import "./TicTacToe.css";

export default perform TicTacToe() {
  // ... part code ...
}
Enter fullscreen mode

Exit fullscreen mode

Right here, we import React and the useState hook from React. The useState hook permits practical parts to handle state.



Step 2: Initialize State Variables

const [turn, setTurn] = useState("X");
const [cells, setCells] = useState(Array(9).fill(""));
const [winner, setWinner] = useState();
Enter fullscreen mode

Exit fullscreen mode

Three state variables are initialized utilizing the useState hook:

  • **flip**: Represents the present participant’s flip (both “X” or “O”).

  • **cells**: An array representing the Tic-Tac-Toe grid, initialized with empty strings.

  • **winner** : Retains monitor of the winner of the sport.



Step 3: Outline Profitable Combos

const combos = {
  throughout: [[0, 1, 2], [3, 4, 5], [6, 7, 8]],
  down: [[0, 3, 6], [1, 4, 7], [2, 5, 8]],
  diagonal: [[0, 4, 8], [2, 4, 6]]
};
Enter fullscreen mode

Exit fullscreen mode

An object combos is outlined to retailer the successful mixtures for Tic-Tac-Toe. It consists of arrays for horizontal, vertical, and diagonal successful patterns.



Step 4: Deal with Cell Clicks

const handleClick = (num) => {
  if (cells[num] !== "") return;

  let arr = [...cells];
  if (flip === "X") {
    arr[num] = "X";
    setTurn("O");
  } else {
    arr[num] = "O";
    setTurn("X");
  }
  checkWinner(arr);
  setCells(arr);
};
Enter fullscreen mode

Exit fullscreen mode

The handleClick perform is known as when a cell is clicked. It updates the sport state based mostly on the present participant’s flip, checks for a winner, and updates the cells state variable.



Step 5: Test for a Winner

const checkWinner = (arr) => {
  for (let combo in combos) {
    combos[combo].forEach((sample) => {
      if (arr[pattern[0]] === "" || arr[pattern[1]] === "" || arr[pattern[2]] === "") {
        // Do nothing if any cell within the mixture is empty.
      } else if (arr[pattern[0]] === arr[pattern[1]] && arr[pattern[1]] === arr[pattern[2]]) {
        setWinner(arr[pattern[0]]);
      }
    });
  }
};
Enter fullscreen mode

Exit fullscreen mode

The checkWinner perform iterates by way of the combos object and checks if any successful mixture is current on the sport board. If a winner is discovered, the winner state variable is up to date with the successful participant’s image.



Step 6: Render Cells and Deal with Reset

const Cell = ({ num }) => {
  const cellValue = cells[num];
  const cellClassName = cellValue ? `cell cell-${cellValue}` : "cell";

  return (
    <td className={cellClassName} onClick={() => handleClick(num)}>
      {cellValue}
    </td>
  );
};

const handleReset = () => {
  setWinner();
  setCells(Array(9).fill(""));
};
Enter fullscreen mode

Exit fullscreen mode

The Cell part renders particular person cells of the Tic-Tac-Toe grid. Every cell’s click on occasion is dealt with by the handleClick perform. The handleReset perform resets the sport by clearing the winner state variable and resetting the cells state variable with empty values.



Step 7: Styling with CSS

.container {
  show: flex;
  flex-direction: column;
  align-items: heart;
  justify-content: heart;
}

desk td {
  border: 1px strong gray;
  width: 100px;
  top: 100px;
}

.cell {
  width: 100px;
  top: 100px;
  text-align: heart;
  font-size: 36px;
  cursor: pointer;
}

.cell-X {
  background-color: #e93737d7;
  shade: #ffffff;
}

.cell-O {
  background-color: #2deb2dc0;
  shade: #ffffff;
}

.winner {
  margin-top: 10px;
  margin-bottom: 10px;
  font-size: 24px;
  show: none;
}

.winner.present {
  show: block;
}

.reset-button {
  margin-top: 20px;
  padding: 10px 20px;
  font-size: 18px;
  border-radius: 5px;
  background-color: #007bff;
  shade: #ffffff;
  border: none;
  cursor: pointer;
}

.reset-button:hover {
  background-color: #0056b3;
}
Enter fullscreen mode

Exit fullscreen mode

CSS kinds are utilized to the parts to create a visually interesting interface. Lessons like cell, cell-X, cell-O, winner, and reset-button are used to fashion the sport cells, winner show, and the reset button.

The hyperlink of the whole code is – https://codesandbox.io/s/tic-tac-toe-z87vh8?file=/src/App.js




Conclusion

By following these steps, the Tic-Tac-Toe sport is constructed utilizing React, combining state administration, occasion dealing with, and CSS styling to create an interactive and visually interesting consumer expertise.



Observe Me on Social Media!

In case you discovered this text useful, be happy to attach with me on LinkedIn and Twitter for extra programming suggestions and tutorials. Let’s be taught and develop collectively!

LinkedIn: https://www.linkedin.com/in/kartikbudhraja/

Twitter: https://twitter.com/K_a_r_t_i_k_08


source