Skip to content

Instantly share code, notes, and snippets.

@bjyoungblood
Created March 29, 2018 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjyoungblood/e595260f61594fad9c45b22462e3f710 to your computer and use it in GitHub Desktop.
Save bjyoungblood/e595260f61594fad9c45b22462e3f710 to your computer and use it in GitHub Desktop.
hoc-to-render-prop-component
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