I'm trying to understand how nested props in React work.
If I have a component A who's parent of a component B who's parent of a component C.
A gives to B a prop foo()
, B gives to C the prop foo()
it got from A.
I call foo()
inside C. What happens?
1)C's foo()
calls B's foo()
who calls A's foo()
2)C's foo()
acts the same as A's foo()
because it IS A's foo()
Imagine that in component A you have a function foo
foo(string) {
console.log(string)
}
and In A
you render component B
and pass foo
as a prop
<ComponetB foo={this.foo}/>
and the same thing for B
<ComponetC foo={this.foo}/>
and in component C
you call
this.props.foo('hey')
this will call component A
function, that will make an console.log('hey')
You can pass foo
as a prop to how many components you want and it will execute what is in the parent component ( A
).
If you will pass something to many nested components, you can use React Context API. Context API will pass a value to all children's of you component as a prop. You should read the documentation to learn more about that.