Skip to content

Instantly share code, notes, and snippets.

@ccnokes
Created February 1, 2019 17:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ccnokes/a06c9908181f18e941e7e5452ebf9024 to your computer and use it in GitHub Desktop.
Save ccnokes/a06c9908181f18e941e7e5452ebf9024 to your computer and use it in GitHub Desktop.
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