Polyfill for the proposed React context API
yarn add create-react-contextYou'll need to also have react and prop-types installed.
constContext=createReactContext(defaultValue);// <Context.Provider value={providedValue}>{children}</Context.Provider>// ...// <Context.Consumer>{value => children}</Context.Consumer>// @flowimportReact,{typeNode}from'react';importcreateReactContext,{typeContext}from'create-react-context';typeTheme='light'|'dark';// Pass a default theme to ensure type correctnessconstThemeContext: Context<Theme> = createReactContext('light');
class ThemeToggler extends React.Component<{children: Node},{theme: Theme}>{state={theme: 'light'};render(){return(// Pass the current context value to the Provider's `value` prop.// Changes are detected using strict comparison (Object.is)<ThemeContext.Providervalue={this.state.theme}><buttononClick={()=>{this.setState(state=>({theme: state.theme==='light' ? 'dark' : 'light'}));}}>
Toggle theme
</button>{this.props.children}</ThemeContext.Provider>);}}classTitleextendsReact.Component<{children: Node}>{render(){return(// The Consumer uses a render prop API. Avoids conflicts in the// props namespace.<ThemeContext.Consumer>{theme=>(<h1style={{color: theme==='light' ? '#000' : '#fff'}}>{this.props.children}</h1>)}</ThemeContext.Consumer>);}}