Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A function that returns a React.Context and a mapContextToProps HOC so that you can inject context onto props, like react-redux's `connect` function
import * as React from 'react';
const defaultMapper = (ctx) => ctx
export function initContext<CtxType>() {
const Context = React.createContext<CtxType | null>(null);
function mapContextToProps<Props>(Component: React.ComponentType<Props & CtxType>, mapper: (ctx: CtxType) => any = defaultMapper): React.ComponentType<Props> {
return (props: Props) => (
<Context.Consumer>
{(ctx) => <Component {...props} {...mapper(ctx)} />}
</Context.Consumer>
)
}
return {
Context,
mapContextToProps,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.