Created
August 7, 2019 09:50
-
-
Save alexeychikk/434f640197baf0b539c80e301dc52092 to your computer and use it in GitHub Desktop.
TypeScript React createContextHOC generic factory
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
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