In a react script, to pass state information from a parent component to a child component, the state information needs to be passed as a prop. For example:
numturns={this.state.number_of_turns}
Now, “numturns” can be used as a prop in the child. For example, inside the child handleclick function:
console.log("Child communication, number of turns from parent: ", this.props.numturns);
Lets say we have the following states set in the parent component:
this.state = { x_locations : [], o_locations : [], x_and_os: ['', '', '', '', '', '', '', '', ''], number_of_turns: 0, currentTurn: 'X', gameInProgress: false, winner: "", gameWon: false, catsGame: false };
In order to pass these states to the child components, they need to be passed to the child element via the parent’s render function, as props. For example, passing state values to child element “Choosefirstplayer”:
<Choosefirstplayer currentTurn={this.state.currentTurn} catsGame={this.state.catsGame} changeTurns={this.changeTurns} setGameInProgress={this.setGameInProgress} gameinprogress={this.state.gameInProgress} newGame={this.newGame} winner={this.state.winner} gameWon={this.state.gameWon} numturns={this.state.number_of_turns}/>
Notice this.state in the right side in the curly braces. This is the passing of the state from the parent to the child component.
The syntax is:
nameofVariable = { this.state.nameofStateVariable }
For complete React code that demonstrates this in action, see my tic-tac-toe react script here:
https://github.com/chris-relaxing/react-tic-tac-toe/blob/master/tic-tac-toe.js