Anthony
Anthony

Reputation: 387

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?

Upvotes: 2

Views: 172

Answers (3)

Usama
Usama

Reputation: 1225

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

Upvotes: 1

Aniket Gund
Aniket Gund

Reputation: 39

It is because of function that you have created is having same name of the prop

Just update the function name in ChildOne.js file

You can check Here Sandbox

Upvotes: 1

Aman Sadhwani
Aman Sadhwani

Reputation: 3658

It's because name of props and your function name is same so update the function name to something onValueTwoPass

Upvotes: 0

Related Questions