I want to let the user enter game mode and pass that data as props to the Board but when I do like below, React just enters the infinite loops. How should I re-organize my code to use setState() for humanFirst and pvp? Any idea is appreciated.
export default class Game extends Component {
constructor(props) {
super(props);
this.state = {
humanFirst: true,
pvp: true,
xIsNext: true,
stepNumber: 0,
history: [
{ squares: Array(9).fill(null) }
]
}
}
render() {
return (
<div>
<Board/>
<div className="game-info">
<label>Choose game mode</label>
<br/>
<select >
<option onSelect={this.setState({
humanFirst: true,
pvp: true
})}>Human vs Human</option>
<option>Human first</option>
<option>AI first</option>
</select>
<br/>
<button type="submit">Start Game</button>
</div>
</div>
)
}
You set the state at the moment the component is rendered, which cause an infinite loop, because changing state causes another render.
<option onSelect={this.setState({
humanFirst: true,
pvp: true
})}>Human vs Human</option>
Instead, you probably want the state to be changed when the event is fired:
<option onSelect={() => this.setState({
humanFirst: true,
pvp: true
})}>Human vs Human</option>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With