Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Kuldeep Bora
Kuldeep Bora

Posted on

     

React's Tic-Tac-Toe using React Hooks

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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Full stack developer. Love front end.
  • Location
    Cyprus
  • Joined

More fromKuldeep Bora

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp