React, call a grandchild component's function from a grandparent component
Unanswered
Virginia's Warbler posted this in #help-forum
Virginia's WarblerOP
I have a component, inside another component, inside another component. I want to call the innermost component's function from the outermost component. How do you do that?
3 Replies
Great Spotted Woodpecker
Hi, you could use react portals or maybe a context api to do that
Could you give an example of what you want to do?
Sometimes, just a code reorganization can help you with that
Could you give an example of what you want to do?
Sometimes, just a code reorganization can help you with that
Exactly if what you need is calling the innermost Component's function you can do that by pure composition
Make the middle child take children:
Make the middle child take children:
function OuterMostComponent() {
const [value1, setValue1] = useState("");
const [value2, setValue2] = useState("");
// ...whatever
return (
<div>
<MiddleComponent propsFromOutermost={value1}>
<InnerMostComponent propsFromOutermost={value2} />
</MiddleComponent>
</div>
);
}
function MiddleComponent({ children, propsFromOutermost}) {
// ...whatever
// children will be the InnerMostChild component
return <div>{children}</div>;
}
function InnerMostComponent({ propsFromOutermost}) {
// ...whatever
return <div>{/* ... */}</div>;
}
@Virginia's Warbler was helpful?