I am trying to mae a tic tac toe game using react. But I am unable to achieve the logic of button being clicable only once. Need some help. Here is the code:
import React, { useRef, useState } from 'react'
let data = ["","","","","","","","",""]
const Board = () => {
let [count, setCount] = useState (0)
const [allow, setAllow] = useState(false)
const [clicked, setClicked] = useState(false)
const title = useRef("")
const toggler = (e, index) =>{
if (allow){
return 0
}
if (count % 2 === 0){
e.target.innerHTML="<h1>X</h1>"
data[index]="x"
setCount(++count)
}
else{
e.target.innerHTML="<h1>O</h1>"
data[index]="o"
setCount(++count)
}
if (index === 0){
setClicked(true)
}
else if (index === 2){
setClicked(true)
}
if (data[0]===data[1] && data[1]===data[2] && data[2]!==""){
won(data[2])
}
else if (data[3]===data[4] && data[4]===data[5] && data[5]!==""){
won(data[5])
}
else if (data[6]===data[7] && data[7]===data[8] && data[8]!==""){
won(data[8])
}
else if (data[0]===data[3] && data[3]===data[6] && data[6]!==""){
won(data[6])
}
else if (data[1]===data[4] && data[4]===data[7] && data[7]!==""){
won(data[7])
}
else if (data[2]===data[5] && data[5]===data[8] && data[8]!==""){
won(data[8])
}
else if (data[0]===data[4] && data[4]===data[8] && data[8]!==""){
won(data[8])
}
else if (data[2]===data[4] && data[4]===data[6] && data[6]!==""){
won(data[6])
}
}
const won=(winner)=>{
setAllow(true)
if (winner === "x"){
title.current.innerHTML="Congrats X won"
}
else if (winner === "o"){
title.current.innerHTML="Congrats O won"
}
else if (count===9){
title.current.innerHTML="It's a draw"
}
}
// const checkWinner = () => {
// }
return (
<>
<h1 ref={title}>Welcome to the Game</h1>
<div className='column'>
<div className="row" onClick={!clicked?((e)=>{toggler(e,0)}):null}></div>
<div className="row" onClick={!clicked?((e)=>{toggler(e,1)}):null}></div>
<div className="row" onClick={!clicked?((e)=>{toggler(e,2)}):null}></div>
</div>
<div className='column'>
<div className="row" onClick={!clicked?((e)=>{toggler(e,3)}):null}></div>
<div className="row" onClick={!clicked?((e)=>{toggler(e,4)}):null}></div>
<div className="row" onClick={!clicked?((e)=>{toggler(e,5)}):null}></div>
</div>
<div className='column'>
<div className="row" onClick={!clicked?((e)=>{toggler(e,6)}):null}></div>
<div className="row" onClick={!clicked?((e)=>{toggler(e,7)}):null}></div>
<div className="row" onClick={!clicked?((e)=>{toggler(e,8)}):null}></div>
</div>
</>
)
}
export default Board