I am passing props from Parent component into Child's state but They are out of sync.
What I tried:
- State Updates May Be Asynchronous, I have taken care of that using a call back instead of returning an object.
- Objects are passed by reference, but the prop i used is a string.
I am using React 16 and es6 syntax
class Parent extends React.Component {
state = {
isHidden: false
}
render() {
console.log('PROPS from PARENT', this.state.isHidden)
return <div>
<Child isOpen={this.state.isHidden} />
<button onClick={this.toggleModal}>Toggle Modal</button>
</div>
}
toggleModal = () => this.setState(state => ({isHidden: !state.isHidden}))
}
class Child extends React.Component {
state = {
isHidden: this.props.isOpen
}
render() {
console.log('STATE of CHILD:',this.state.isHidden)
return <p hidden={this.state.isHidden}>Hidden:{this.state.isHidden}</p>
}
}
ReactDOM.render(<Parent/>, document.getElementById('app'));
Here a codepen PEN - notice the redered element is supposed to be hidden based on the state(state depends on props from parent)