Good day. I'm building a tree of components and want to use functions of root component in other components of tree. I throw function reference through all tree. Also I use the object if me need get value from the function in not root componet. Can you help me? Can you show me how to do this as HOC ? If it will be not so hard for you show examples on my code.
import React from 'react';
class Page extends React.Component{
Answer = {
value : ''
}
doSomething(){
console.log(this.Answer.value);
console.log('Ready!');
}
render(){
return(
<div>
<div>
<Body
ParentFunc={()=>this.doSomething()}
ParentParameters={this.Answer}
/>
</div>
</div>
)
}
}
export default Page
class Body extends React.Component{
render(){
const{
ParentFunc,
ParentParameters
} = this.props
return(
<div>
<div>
<SomeComponent
ParentFunc={()=>ParentFunc()}
ParentParameters={ParentParameters}
/>
</div>
</div>
)
}
}
class SomeComponent extends React.Component{
getAnswer(){
const{
ParentFunc,
ParentParameters
} = this.props
ParentParameters.value = 'Some text'
ParentFunc()
}
render(){
return(
<div onClick={()=>this.getAnswer()}>
We can?
</div>
)
}
}
I don't believe a Higher Order Component alone will solve your basic issue of prop drilling. A React Context would be a better fit for providing values and functions generally to "want to use functions of root component in other components of tree".
Start by creating your Context and Provider component:
Render
QnAProvider
in your app somewhere wrapping the React subtree you want to have access to the values being provided:Consuming the Context:
Class-based components consume contexts via the render props pattern.
Functional components can use the useContext React hook
Here is where using a Higher Order Component may become useful. You can abstract the
QnAContext.Consumer
render props pattern into a HOC:Then you can decorate components you want to have the context values injected into.
Note: The point of doing all this was to move the values and functions that were previously defined in
Page
into the Context, so they are no longer passed fromPage
thoughBody
toSomeComponent
(or any other children components).Demo
Sandbox Code: