Created
February 1, 2019 17:46
-
-
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
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 * 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