Skip to content

Instantly share code, notes, and snippets.

@juandjara
Last active August 29, 2018 17:33
Show Gist options
  • Save juandjara/78cf0cac7c864ede2fa0fc95c5417fcf to your computer and use it in GitHub Desktop.
Save juandjara/78cf0cac7c864ede2fa0fc95c5417fcf to your computer and use it in GitHub Desktop.
Utils for React 16 Context API.
// 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