A Really Simple Intro to Lifting State in React
Laura Todd
Posted on April 25, 2021
When using React, you can easily share information downwards in the component tree. Using props, you're able to pass data from a parent component to a child component but how do you pass information from a child to a parent or even between siblings?
That's when we need to lift state. I'll take you through a basic example.
Lets say you have an App component with two child components. One is a dropdown menu which allows the user to choose their favourite holiday destination and the other is a coloured box which should display the user's choice.
You can find the starting code here.
So here's the structure of our app -
And we want to pass information from Dropdown.js to Chosen.js -
But we can't do that directly, so we need to get the information up to App.js and then down again to Chosen.js -
The way we do this is to set the state in App.js rather than in Dropdown.js. We do this exactly as we would if we were doing it within the child component.
Begin by initialising the state of the chosen option. You can call it what you like but I'm going to call it 'chosen'.
Next, create an event handler for the onChange event of the dropdown menu. This will set the state of 'chosen' to the chosen value from the dropdown menu -
Don't forget to bind the function in the constructor. So you should have this at the top of your App component -
Now we need to connect the event handler to the Dropdown component so let's go over to the Dropdown.js file and add the onChange property to the <select>
tags. We do this by adding "{props.onChoose}". The "onChoose" part an be called anything you like, this will just be what you use as the property name within the App component.
Then we can go back to App.js and add the "onChoose" property to the Dropdown component and set its value to "{this.handleChange}" (the event handler that we set up earlier).
Next, let's go over to the Chosen.js file and "{props.choice}" within some <p>
tags. This will display the chosen destination.
Finally, go back to the App.js file and add "choice={this.state.chosen}" to the Chosen component. This will mean that whatever the current state of "chosen" is will be displayed in the paragraph tags of the Chosen component.
Now, you can run your app and see your choice displaying in the blue box -
You can check your final code here.
Posted on April 25, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.