Last active
June 14, 2019 02:10
-
-
Save jmoore53/632c97a875db8abd0fdaf7d5db8d7c04 to your computer and use it in GitHub Desktop.
Example of passing state among multiple components.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Parent extends Component { | |
constructor(props){ | |
super(props); | |
this.state = {passedValue: this.props.passedFromStaticView}; | |
this.handleParentStateUpdate = this.handleParentStateUpdate.bind(this); | |
} | |
// This method is passed as a prop to the child component | |
handleParentStateUpdate(e){ | |
console.log("handle state update for the parent!") | |
// Sets the state of this class's passedValue variable | |
this.setState({passedValue: e}) | |
} | |
render () { | |
return ( | |
<React.Fragment> | |
<Child passedValue={this.state.passedValue} handleParentStateUpdate={this.handleParentStateUpdate} /> | |
</React.Fragment> | |
); | |
} | |
} | |
class Child extends Component { | |
constructor(props){ | |
super(props); | |
this.state = {passedValue: this.props.passedValue} | |
this.handleChildStateUpdate = this.handleChildStateUpdate.bind(this); | |
} | |
handleChildStateUpdate(e){ | |
// Update the state of the Child Component | |
this.setState({passedValue: e}) | |
// Calling the method that was passed down from the `Parent` class as a prop | |
this.props.handleParentStateUpdate(e) | |
} | |
render(){ | |
return( | |
<React.Fragment> | |
<Child passedValueFromChild={this.state.passedValue} handleParentStateUpdate={this.handleChildStateUpdate} /> | |
</React.Fragment> | |
) | |
} | |
} | |
class GrandChild extends Component { | |
constructor(props){ | |
super(props); | |
this.state = {passedValue: this.props.passedValueFromChild} | |
this.handleChildStateUpdate = this.handleChildStateUpdate.bind(this); | |
} | |
handleChildStateUpdate(e){ | |
// Update the state of the GrandChild Component | |
this.setState({passedValue: e}) | |
// Calling the method that was passed down from the `Child` class as a prop | |
this.props.handleParentStateUpdate(e) | |
} | |
render(){ | |
return( | |
<React.Fragment> | |
<button onClick={(e) => this.handleChildStateUpdate("State")} className="btn btn-warning"> | |
Update State | |
</button> | |
</React.Fragment> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment