I'm new to React. As a learning exercise I'm building an chess application
I want to change the DOM of child based on state in parent. Currently there is no change in child components on change of state in parent.
Parent Component
class Game extends Component{
constructor(){
super();
this.state = {
game :{
board_position = { 'One' : ''}
}
}
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
let p = this.state.game.board_position;
// some computations on p
p = { board_position : { 'One' : Math.random() } }
this.setState({
game : p
})
//this.forceUpdate(); // Just trying different methods to make it work
}
render(){
return(
<div onClick={(e) => this.handleClick(e) }>
<Piece {...this.state.game.board_position} />
</div>
)
}
}
Child Component
Class Piece extends Component{
constructor(){
super(props);
this.state = {
clr : ''
}
}
componentWillMount(){
let c;
// some computations that change value of c based on props
if( typeof ( this.props.game.one) == number ){
c = 'Red'
} else {
c = 'Blue'
}
this.setState({
clr : c
})
}
render(){
return(
<span>{this.state.clr}</span>
)
}
}
On call of handle click method, there is a change in state of the game. However, subsequent changes in Child are not seen.
Can anyone please help me out? Where am I going wrong?
I'm not sure how to implement ref as suggested over here. However, I don't think that is a good solution. Probably I'm having some conceptual misunderstanding.
PS: Please ignore any syntax error. This code is a strip down of real code. If you want to take a look at full code - go over here