Skip to content
Advertisement

How to pass values to parent from child of child?

I have a parent component, with a child, which also has a child.

Parent
|-Child One (child of parent)
  |-Child Two (child of child)

When a value is defined in child two, I am passing that value using a callback to child one, but I also want to pass the same value back to the parent. Unfortunately using a similar callback seems two throw the error that the identifier has already been declared.

Please see the sandbox to see how exactly I am trying to implement it.

CodeSandbox

How do I do that?

Advertisement

Answer

Since ChildTwo component needs to update both its parent ChildOne and grand-parent App. This can be done in two ways.

One way is that, you create another state in ChildOne and pass its state function setValueTwo along with App state function valueTwoPass to ChildTwo. ChildTwo now can set values for parent and grand-parent.

  1. Example

Second method is that, you do not create another state in ChildOne. Since, you need to show same value for both parent and grand-parent component, you can pass state value valueTwo to ChildOne like this

<ChildOne valueOnePass={valueOnePass} valueTwoPass={valueTwoPass} valueTwo={valueTwo} />

When ChildTwo updates the state value of grand-parent App, valueTwo also changes in ChildOne since App is also passing valueTwo as its props.

Then just use valueTwo variable in ChildOne instead of creating new state and passing to ChildTwo.

  1. Example
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement