Created
May 26, 2021 12:07
-
-
Save KonradSzwarc/0765b88d7b9656fc7a1b3f08156dc043 to your computer and use it in GitHub Desktop.
HOC that allows to use React hooks with class components.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { ReactElement, ComponentType } from 'react'; | |
function withHook<HookReturn extends Record<string, unknown>>(use: () => HookReturn) { | |
return <Props extends Record<string, unknown>>( | |
Component: ComponentType<Props & HookReturn>, | |
): ComponentType<Props> => { | |
const WrappedComponent = (props: Props): ReactElement<Props & HookReturn> => { | |
const hookProps = use(); | |
return <Component {...props} {...hookProps} />; | |
}; | |
WrappedComponent.displayName = Component.displayName || Component.name; | |
return WrappedComponent; | |
}; | |
} | |
export default withHook; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment