Home > Net >  Is there a way to make a tic tac toe app using React functions
Is there a way to make a tic tac toe app using React functions

Time:12-03

The main problem is that my tic tac toe board is not updating when I click on the square inside the board. It seems that the useState function; setXIsNext is working. But I don't know if setGame function is working or not.

I tried to remove the slice function but it still didn't update. I tried putting

dupGame[i] = xIsNext ? 'X' : 'O'

into setGame function which updated the 1st square in the board but not the square that was clicked.

Code Used:

import { useState } from 'react'
import './tiktacktoe.css'
function Square(props) {
    return (
        <div className="square" onClick={props.onClick}>
            {props.value}
        </div>
    )
}
function Board(){
    const [game, setGame] = useState(Array(9).fill(null))
    const [xIsNext, setXIsNext] = useState(true)
    
    function handleClick(i) {
        const dupGame = game.slice()
        if (dupGame[i]) {
            return
        }
        dupGame[i] = xIsNext ? 'X' : 'O'
        setXIsNext(!xIsNext)
        setGame(dupGame)
    }
    function renderSquare(i){
        return (
            <Square value={game[i]} onClick={handleClick} id={i} />
        )
    }
    
    let board = []
    for (let i = 0; i < 9; i  ) {
        board.push(renderSquare(i))
    }
    let status = "Next player: "   (xIsNext ? 'X' : 'O')
    return (
        <div >
            <div>
                {status}
            </div>
            <div className='board'>
                {board}
            </div>
        </div>
    )
}
export function TikTackToe() {
    
    return (
        <div>
            <Board/>
        </div>
    )
}

CodePudding user response:

youre onclick function is wrong, when called the event is passed to the function.

try

<Square value={game[i]} onClick={() => handleClick(i)} id={i} />
  • Related