Reputation: 3439
I'm building a higher order component for my various React components. In this HOC, I need to access the child's methods and call them. How can I do it?
example HOC:
export default function withHOC(Component) {
return class extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
if (Component.someFunction) {
Component.someFunction()
}
}
render() {
return <Component {...this.props} />;
}
};
}
example component:
class App extends React.Component {
someFunction() {
console.log("something done here, for example setState")
}
render() {
return (
<div></div>
);
}
}
// then it's used like this
export default withHOC(App)
I know that in some case it might not even make sense to solve it like this, but for example framework Next.js can do something similar with it's getInitialProps function.
Upvotes: 3
Views: 3546
Reputation: 281646
Since you want to call the child components method in componentDidMount of HOC, a better alternative is to indeed call the method in the componentDidMount
of the component itself, which would take care of the case when the child component doesn't have a function or if it is composed of multiple HOCs like
export default function withHOC(Component) {
return class extends React.Component {
constructor(props) {
super(props);
}
render() {
return <Component {...this.props} />;
}
};
}
class App extends React.Component {
componentDidMount() {
this.someFunction();
}
someFunction() {
console.log("something done here, for example setState")
}
render() {
return (
<div></div>
);
}
}
However if you still want to call the function in child component, you would make use of refs(however if the App component is composed of other HOCs, this won't work)
export default function withHOC(Component) {
return class extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
this.cmp.someFunction();
}
render() {
return <Component ref={(ref) => this.cmp = ref} {...this.props} />;
}
};
}
class App extends React.Component {
someFunction() {
console.log("something done here, for example setState")
}
render() {
return (
<div></div>
);
}
}
Upvotes: 5
Reputation: 10204
If you replace :
if (Component.someFunction) {
Component.someFunction()
}
By :
if (this.someFunction) {
this.someFunction();
}
You should be able to access you component instance function.
Also, next.js getInitialProps function is static, that's why you can access it directly from the component class.
Upvotes: 2