In some scenarios lets assume you have to, use React hook concept in react class based components.
But as you know react hooks only going to work in functional component if you wish to directly using them in class based component.
it will through an error.
So how to do it, there is a work around solution for the same.
There are 3 step solution
Create a custom Hook
import {useState} from 'react'; const useGreet = () => { const [text, setText] = useState(''); //... do any additional operation / hooks you want to add return text; }
Creating a Higher Order Component
// import useGreet export const MyHigherOrderComponentDemo = (Component) => { return (props) => { const text = useGreet(); return <Component text={text} {...props}/>; } }
Wrap Higher Order Component in class based component
// import useGreet class MyClass extends React.component { render() { return ( <p>{this.props.text}</p> ) } } export default MyHigherOrderComponentDemo(MyClass);
The above is the detailed content of React Hook in Class Component. For more information, please follow other related articles on the PHP Chinese website!