Hello All,
As I am learning react hooks, this is my take in changing react's tic-tac-toe game code to use hooks.
I will jump straight to code as the documentation in reactjs.org is one of the best I've ever seen.https://reactjs.org/tutorial/tutorial.html#what-are-we-building
Functions remains same as their class counterpart:
Square(props), Board(props) and calculateWinner(squares)
The "Game" component is changed to functional component and is using hooks now.
constGame=()=>{const[history,setHistory]=React.useState([{squares:Array(9).fill(null)}]);const[stepNumber,setStepNumber]=React.useState(0);const[xIsNext,setXIsNext]=React.useState(true);const[status,setStatus]=React.useState("");consthandleClick=(i)=>{consthist=history.slice(0,stepNumber+1);constcurrent=hist[hist.length-1];constsquares=current.squares.slice();if(calculateWinner(squares)||squares[i]){return;}squares[i]=xIsNext?"X":"O";setHistory(hist.concat([{squares}]));setStepNumber(hist.length);setXIsNext(!xIsNext);}constjumpTo=(step)=>{setStepNumber(step);setXIsNext((step%2)===0);}constmoves=history.map((step,move)=>{constdesc=move?'Go to move #'+move:'Go to game start';return(<likey={move}><buttononClick={()=>jumpTo(move)}>{desc}</button></li>);});letcurrent=history[stepNumber];letwinner=0;React.useEffect(()=>{current=history[stepNumber];winner=calculateWinner(current.squares);if(winner){setStatus("Winner:"+winner);}else{setStatus("Next player:"+(xIsNext?"X":"O"));}});return(<divclassName="game"><divclassName="game-board"><Boardsquares={current.squares}onClick={i=>handleClick(i)}/></div><divclassName="game-info"><div>{status}</div><ol>{moves}</ol></div></div>);}
I am updating the status and calculating the winner in a useEffect hook as this will be called at every render (update).
The working code:https://codepen.io/kuldeep-bora/pen/QWbWPrY
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse