Created
February 25, 2020 15:27
-
-
Save vinilios/66f94315bb76c6891216201b5ee11867 to your computer and use it in GitHub Desktop.
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
// 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