Created
March 29, 2018 19:50
-
-
Save bjyoungblood/e595260f61594fad9c45b22462e3f710 to your computer and use it in GitHub Desktop.
hoc-to-render-prop-component
This file contains 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
type HOC<InputProps, EnhancedProps> = (component: React.ComponentType<InputProps & EnhancedProps>) => | |
React.ComponentType<InputProps>; | |
type RenderPropProps<InputProps, EnhancedProps> = { | |
[P in keyof InputProps]: InputProps[P]; | |
} & { | |
children: (props: EnhancedProps) => React.ReactNode; | |
}; | |
type RenderProp<InputProps, EnhancedProps> = React.ComponentType<RenderPropProps<InputProps, EnhancedProps>>; | |
function hocToRenderPropComp<InputProps, EnhancedProps>( | |
hoc: HOC<InputProps, EnhancedProps>, | |
): RenderProp<InputProps, EnhancedProps> { | |
const Enhanced = hoc((props: EnhancedProps) => { | |
// cast props to any as TS doesn't currently support rest/spread on generics | |
const { children, ...rest } = props as any; | |
return children(rest as EnhancedProps); | |
}); | |
return (props) => <Enhanced {...props} />; | |
} | |
function autoRenderCompWithHOC<InputProps, EnhancedProps>( | |
hoc: HOC<InputProps, EnhancedProps>, | |
Component: React.ComponentType<InputProps & EnhancedProps>, | |
): React.ComponentType<InputProps> { | |
const RenderComp = hocToRenderPropComp<InputProps, EnhancedProps>(hoc); | |
return (props) => ( | |
<RenderComp {...props}> | |
{(result) => <Component {...result} />} | |
</RenderComp> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment