Last active
August 29, 2018 17:33
-
-
Save juandjara/78cf0cac7c864ede2fa0fc95c5417fcf to your computer and use it in GitHub Desktop.
Utils for React 16 Context API.
This file contains hidden or 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
// Proivder usage example: | |
// <ContextProvider> <MyApp></MyApp> </ContextProvider> | |
// TIP: The ContextProvider component must be placed above the router component if you use a router. | |
// Consumer usage example: | |
// export default withContext(MyComponent); | |
// now `context` gets passed to `MyComponent` as a prop. | |
// the context prop has two methods `get` and `set` that can read and update the state of the context provider component | |
import React, { createContext, Component } from 'react'; | |
const Context = createContext({ | |
get: key => { | |
return this.state[key]; | |
}, | |
set: (key, value) => { | |
this.setState({ [key]: value }); | |
} | |
}) | |
export const ContextConsumer = Context.Consumer; | |
export class ContextProvider extends Component { | |
state = { | |
get: key => { | |
return this.state[key]; | |
}, | |
set: (key, value) => { | |
this.setState({ [key]: value }); | |
} | |
} | |
render() { | |
return ( | |
<Context.Provider value={this.state}> | |
{this.props.children} | |
</Context.Provider> | |
) | |
} | |
} | |
export function withContext(WrappedComponent) { | |
const ContextWrapper = (props) => ( | |
<ContextConsumer> | |
{context => <WrappedComponent {...props} context={context} />} | |
</ContextConsumer> | |
); | |
return ContextWrapper; | |
} | |
export default { withContext, ContextConsumer, ContextProvider }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment