Last active
January 9, 2017 23:35
-
-
Save ingesolvoll/101256657c664581832db5a231178cc7 to your computer and use it in GitHub Desktop.
The React Tic tac toe tutorial
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Square(props) { | |
return ( | |
<button className="square" onClick={() => props.onClick()}> | |
{props.value} | |
</button> | |
); | |
} | |
class Board extends React.Component { | |
constructor() { | |
super(); | |
this.state = this.vanillaState(); | |
} | |
vanillaState () { | |
return {squares: Array(9).fill(null), | |
xIsNext: true}; | |
} | |
reset () { this.setState(this.vanillaState()) } | |
renderSquare(i) { | |
return (<Square value= {this.state.squares[i]} onClick= {() => this.handleClick(i)}/>); | |
} | |
handleClick(i) { | |
if (this.state.squares[i]) { return; } | |
const squares = this.state.squares.slice(); | |
squares[i] = this.state.xIsNext ? 'X' : 'O'; | |
this.setState({squares: squares, | |
xIsNext: !this.state.xIsNext}); | |
} | |
render() { | |
let status = `Next player: ${this.state.xIsNext ? 'X' : 'O'}`; | |
return ( | |
<div> | |
<div className="status">{status}</div> | |
<div className="board-row"> {[0,1,2].map ((i) => this.renderSquare(i))} </div> | |
<div className="board-row"> {[3,4,5].map ((i) => this.renderSquare(i))} </div> | |
<div className="board-row"> {[6,7,8].map ((i) => this.renderSquare(i))} </div> | |
<button onClick= {() => this.reset()}> Reset </button> | |
</div> | |
); | |
} | |
} | |
window.BoardWithPlayers = Board; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment