create-react-context
Polyfill for the proposed React context API
Install
yarn add create-react-context
You'll need to also have react
and prop-types
installed.
API
const Context = createReactContext(defaultValue);
Example
import React, { type Node } from 'react';
import createReactContext, { type Context } from 'create-react-context';
type Theme = 'light' | 'dark';
const ThemeContext: Context<Theme> = createReactContext('light');
class ThemeToggler extends React.Component<
{ children: Node },
{ theme: Theme }
> {
state = { theme: 'light' };
render() {
return (
<ThemeContext.Provider value={this.state.theme}>
<button
onClick={() => {
this.setState(state => ({
theme: state.theme === 'light' ? 'dark' : 'light'
}));
}}
>
Toggle theme
</button>
{this.props.children}
</ThemeContext.Provider>
);
}
}
class Title extends React.Component<{ children: Node }> {
render() {
return (
<ThemeContext.Consumer>
{theme => (
<h1 style={{ color: theme === 'light' ? '#000' : '#fff' }}>
{this.props.children}
</h1>
)}
</ThemeContext.Consumer>
);
}
}