React State and Props Explained Through George Washington Cutting Down the Cherry Tree

To help you understand props and state in parent and child components in react.js, I’ll use an example of an actual parent and child relationship, more specifically the parent-child relationship between our first president George Washington and his parents Mary and Augustine. George Washington is a very honest man as we all know, and tells his parents every time he does something bad and in this example he also tells them when he does something good. On a very basic level George has two states he’s in with his parents, inTrouble=true and inTrouble =false. Before he famously cut down his parents’ cherry tree he was in the state of inTrouble=false with his parents or his parent component. Let’s set up the parent component with a constructor function that sets the state of inTrouble.

Class Parent extends Component {
 constructor(){
super();
this.state = {
inTrouble: false
}
}
updateTrouble(status) {
the.setState({
inTrouble: status
})
}
render(){
return(
<Child
trouble=this.updateTrouble(true) noTrouble=this.updateTrouble(false)
/>
)}

Now we can pass the updateTrouble function that changes the inTrouble state to our child component, George Washington, through the prop, trouble.

Class Child extends Component {
cutDownCherryTree (){
this.props.trouble
}
   plantNewCherryTree (){
this.props.noTrouble
}
}
render(){
return(
<button onClick=this.cutDownCherryTree>Cut Down</button>
<button onClick=this.plantNewCherryTree> Plant</button>
)}

In our render function we have two buttons, Cut Down and Plant. Cut Down sets off our Child component’s cutDownCherryTree function onClick. Within that function we access the Child’s props, trouble. The trouble props of the Child component sets off the Parent component’s updateTrouble function and passes it the value true as the argument. That argument is then set as the state of inTrouble by this.setState.

If you think about this passing of state up to the Parent component’s constructor function in the real world scenario, clicking the button is equivalent to George Washington cutting down the tree. Then, because George was such an honest man, he immediately went and told his parents. This is equivalent to us using props in the Child component to set off the function updateTrouble in the Parent component. Once updateTrouble is set off the state of inTrouble is set to the argument that is passed through, which is either true or false depending on whether you decided to make George cut down the cherry tree or plant a new one. In this case we cut down the cherry tree so George Washington is inTrouble = true.