ReactJS: Change the state of the component from the parent component

Tram Ho

1. Introduction:

If you work with ReactJS, you will find that Props and State are heavily used. Like Props, State is used to store component information, the difference is that State is a component of component and Props is value passed from outside to component. We usually update the state right in the component with the command setState () to re-render the component, So in case we want to change the state from the parent component, how to solve it ????
A fairly simple solution is to use Refs in React. Let’s take a look at the example below to see more clearly !!!

2. For example:

We will perform an example that changes the name of a child component by performing a button click on the parent component.
Come on go !!!
First, we will create a component named ChildComponent whose state is name with an initial value of ” Diem My “. The component will display the text “My name is” and the name is taken from the state.

Next, to make a state change, we will create a function changeName () and use this.setState () to change the state:

ChildComponent now has a state and a function that changes state, currently it will look like this:

Next, we will create a parent component named ParentComponent that will not yet have ChildComponent , a button to make name changes when clicked, and a temporary function that will be blank for a moment we will handle to change the state in ChildComponent :

It’s time we need to use Refs for ChildComponent named childRef . Refs help us to refer to the ChildComponent node using. current . It will print out everything related to ChildComponent and also changeName () . Now we just need to use changeName () in handleClick () to make state changes.

Tada, so our example is complete. You can see the code and run here, CodeSanbox

3. Conclusion

Now changing the State by action outside the component has become simple when there are Refs right?

References:

Share the news now

Source : Viblo