I am able to see a lot of threads explaining how to use a custom hook inside a class component using a higher-order component, In that case, we are using a Hooks output value inside the class component.
Is there any way we can invoke a hook inside the class component while using HOC? because sometimes the hooks are accepting some parameters. and the parameters for that function are based on the state of a class component
Accessing the hook value inside the class component
import React from 'react';
import { withSampleHookHoc } from './withSampleHookHoc';
class SampleClassComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'Guest',
};
}
render() {
return <h1> Sample Class Component - {this.props.name} </h1>;
}
}
export default withSampleHookHoc(SampleClassComponent);
But what I want to have is passing the state value as a parameter to the hook and invoking it from the class component
import React from 'react';
import { withSampleHookHoc } from './withSampleHookHoc';
class SampleClassComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
text: 'Guest',
};
}
render() {
return <h1> Sample Class Component - {this.props.name(this.state.text)} </h1>;
}
}
export default withSampleHookHoc(SampleClassComponent);
Code URL
Yes you certainly can. Stackblitz example here: https://stackblitz.com/edit/react-bgum6q?file=src/Components/SampleClassComponent.js. Edit the input then click the Update name button to see it works.
Essentially, you just return some function from your hook, which will be passed to the class component as a prop via the HOC. Then, you have access to this function inside your class component and can do whatever you like.
If you have any questions, just add a comment to this answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With