Skip to content Skip to sidebar Skip to footer

Can a Parent Take a Child Out of State

past Johny Thomas

How to modify the state of a kid component from its parent in React

VSHQltaIS4A-WnEWL9SHecUzng1v8VSqbSDM
Photo by Clément H (@clemhlrdt) on Unsplash

Nosotros will exist edifice a simple React app which shows the real name of a superhero on a button click.

Let's become started.

First, we will create a Superhero component with a proper noun attribute in land. This component volition render that proper name get-go.

dXk6uX7LQOfLuMWqTAqOZSd7obn-GESaMUkA

At present permit's create a function changeName() in the Superhero component. This function will alter the name in land to the actual name of the superhero.

-3-r39-jq60PNryomLCF7ShV4sHJEOhBBDtl

Now nosotros have the Superhero component which shows the superhero name and a role which updates the proper noun to his existent name.

The complete Superhero component will look similar this:

yHRO4tad52gX20O9uRC38b-oSgiRe5VK9f6m

Now let's create the App component which volition render this Superhero component and a button. When nosotros click the button information technology shows the real superhero name.

vlplStkM5jX8jKzIgUuOZB3ezux7mORUNvMy

We have added a role handleClick() which will get called when the user clicks the button. We demand to figure out a way to update the land of the kid component, that is the Superhero component.

We have created a function changeName() in the Superhero component. This function will show the existent name of the superhero. If we can phone call this function from the App component, our work is done. So we will call this function.

Hither is where refs come to our rescue.

Allow's create a ref of the Superhero component in the App component. Here is the code for doing that.

gYY7kDmcNbMT1flktY70lOgXYmqRZAjRErUN

Here nosotros have created a ref using React.createRef() method and attached the ref to the Superhero component using the ref attribute.

Now we will be able to refer the Superhero node using this.superheroElement.current. We will also exist able to phone call the changeName() function in the Superhero component using this.superheroElement.current.changeName().

Allow's update our handleClick() function in our App component to call the changeName() office.

Our handleClick() function will look like this.

Qx7hBSPn7YlzdtGpDSC7Dcr4bP6wR5CKGFOr

Yous can check out the complete lawmaking in the below sandbox.

CodeSandbox
CodeSandbox is an online editor tailored for web applications.codesandbox.io

Now we take learned how to update the land of a child component from a parent component ?. I promise this was helpful.


Larn to lawmaking for free. freeCodeCamp's open source curriculum has helped more xl,000 people become jobs every bit developers. Get started

huffmaneverstaid.blogspot.com

Source: https://www.freecodecamp.org/news/react-changing-state-of-child-component-from-parent-8ab547436271/

Post a Comment for "Can a Parent Take a Child Out of State"