Is it possible to pass data up several levels of child -> parent and do something with that data at each stage without creating new functions at each level? For example, if I have three levels of component:
PARENT
function Parent() {
const parentFunction = (str) => {
console.log('Output processed by parent', str)
};
return (
<div>
<Child onClick={parentFunction} />
</div>
);
}
CHILD
function Child({passedFunc}) {
// DO SOMETHING HERE WITH THE RESULT OF ONCLICK BEFORE PASSINT IT UP
// TO PARENT
return (
<div>
<GrandChild onClick={passedFunc} label="first" />
<GrandChild onClick={passedFunc} label="second" />
</div>
);
}
GRANDCHILD
function GrandChild({passedFunc, label}) {
const handle_click = () => {
passedFunk(label + 'something');
}
return (
<div onClick={handle_click}>{label}</div>
);
}
When the grandchild
is clicked a string is passed up two levels to parent
where it is printed to console. But I also want to be able to do something with that data at the first child
level before it is passed up and still printed.
2
Answers
Yes you can do something like this
Not sure if this is what you want, but in general you can intercept value of the callback at any layer. But when it becomes too deep, there are several ways to handle it and one of the is to use context (docs).