Skip to content

Instantly share code, notes, and snippets.

@vinilios
Created February 25, 2020 15:27
Show Gist options
  • Save vinilios/66f94315bb76c6891216201b5ee11867 to your computer and use it in GitHub Desktop.
Save vinilios/66f94315bb76c6891216201b5ee11867 to your computer and use it in GitHub Desktop.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function withContextProps<P, C extends React.Context<any>>(
component: React.FC<P>,
context: C,
hook?: (a: React.ContextType<C>, b: P) => Partial<P>
): React.FC<P> {
type CP = React.ContextType<C>;
type UP = CP & P;
const commonHook = (ctx: CP | null, p: P): UP => {
return ctx ? { ...ctx, ...p } : (p as UP);
};
return (props: P): ReturnType<React.FC<P>> => {
const ctx = useContext(context);
const finalProps = useMemo<P>((): P => {
const finalCtx = hook ? hook(ctx, props) : commonHook(ctx, props);
return { ...finalCtx, ...props };
}, [props, ctx]);
return component(finalProps);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment