Introduction
In this challenge you will learn how to develop a tic-tac-toe board game using react basic concepts with little JS programming logic around that.
In this challenge you will learn how to develop a tic-tac-toe board game using react basic concepts with little JS programming logic around that.
To get started, open the editor. You can see the following files from your editor.
├── public
├── src
│ ├── components
│ │ ├── common
│ │ │ └── Utils.js
│ │ ├── Board.js
│ │ ├── Game.js
│ │ └── Square.js
│ ├── App.css
│ ├── App.js
│ ├── App.test.js
│ ├── index.css
│ ├── index.js
│ ├── logo.svg
│ ├── reportWebVitals.js
│ └── setupTests.js
├── package-lock.json
└── package.json
To install the project dependencies, use the following command:
npm i
Please complete this challenge in the src/components/Game.js
file.
Use the useState
hook to define three state variables: board, xTurn, and winner.
board
represents the state of the game board. It is initialized as an array of 9 elements, where each element is initially set to null.xTurn
is a boolean flag indicating whether it is currently X's turn.winner
stores the result of the calculateWinner
function, which determines the winner based on the current state of the board.The handleClick
function is called when a square on the game board is clicked.
[...board]
) and assigns it to tmpBoard.tmpBoard[i]
is truthy), the function returns without making any changes.tmpBoard
to either "X" or "O" based on the value of xTurn
.tmpBoard
is then set as the new value for the board state using setBoard
, and xTurn is toggled using setXTurn.Once you have completed the code, run it with the following command:
npm start
The finished result is as follows:
Congratulations! You have completed the Tik Tac Toe You can practice more challenge in LabEx to improve your skills.