Skip to content

Instantly share code, notes, and snippets.

@alexeychikk
Created August 7, 2019 09:50
Show Gist options
  • Save alexeychikk/434f640197baf0b539c80e301dc52092 to your computer and use it in GitHub Desktop.
Save alexeychikk/434f640197baf0b539c80e301dc52092 to your computer and use it in GitHub Desktop.
TypeScript React createContextHOC generic factory
import React from "react";
/*
// Usage:
export type WithPleasure = {
pleasure: number;
};
const PleasureContext = React.createContext<WithPleasure>({
pleasure: 13
});
const withPleasure = createContextHOC(PleasureContext.Consumer);
// ...somewhere in your component
type Props = WithPleasure & { myProp: string };
class YourComponent extends React.Component<Props> { ... }
export default withPleasure(YourComponent);
*/
export const createContextHOC = <Context extends object>(
Consumer: React.Consumer<Context>,
) => {
const withContext = <P extends Context>(
Component: React.ComponentType<P>,
) => {
return class WithContextHOC extends React.Component<
Omit<P, keyof Context> & Partial<Context>
> {
public render() {
return <Consumer>{this.renderComponent}</Consumer>;
}
private renderComponent = (ctx: Context) => {
const newProps = { ...ctx, ...this.props };
return <Component {...(newProps as P)} />;
};
};
};
return withContext;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment