I’ve been following the tutorial for a tic tac toe game, the basic introduction at reactjs.org, it occurred to me rather than replacing the square with an ‘X’ I should be able to add a function to roll a random number between 1-6 as if rolling a dice.
but being new to REACT, JSX & ES6, I’m not sure how to pass this function in… any additional explanation would be appreciated.
on line 10, they change the square’s content to an X, so I’m thinking that’s where I should write the function, but it also looks like they break that out into a helper function later in the tutorial… so that might be considered better practice, I’ve even found an NPM Dice module I’d like to play with next, but I want to understand the basic’s first before I start trying to add that.
class Square extends React.Component {
constructor(props) {
super(props);
this.state = {
value: null,
};
}
render() {
return (
<button className="square" onClick={() => this.setState({value: 'X'})}>
{this.state.value}
</button>
);
}
}
class Board extends React.Component {
renderSquare(i) {
return <Square value={i} />;
}
render() {
const status = 'Next player: X';
return (
<div>
<div className="status">{status}</div>
<div className="board-row">
{this.renderSquare(0)}
{this.renderSquare(1)}
{this.renderSquare(2)}
</div>
<div className="board-row">
{this.renderSquare(3)}
{this.renderSquare(4)}
{this.renderSquare(5)}
</div>
<div className="board-row">
{this.renderSquare(6)}
{this.renderSquare(7)}
{this.renderSquare(8)}
</div>
</div>
);
}
}
class Game extends React.Component {
render() {
return (
<div className="game">
<div className="game-board">
<Board />
</div>
<div className="game-info">
<div>{/* status */}</div>
<ol>{/* TODO */}</ol>
</div>
</div>
);
}
}
// ========================================
ReactDOM.render(
<Game />,
document.getElementById('root')
);