Name: react-context-composer
Owner: Formidable
Description: Clean composition of React's new Context API
Created: 2017-12-08 16:27:13.0
Updated: 2018-02-13 18:27:46.0
Pushed: 2017-12-14 15:02:32.0
Homepage: null
Size: 39
Language: JavaScript
GitHub Committers
User | Most Recent Commit | # Commits |
---|
Other Committers
User | Most Recent Commit | # Commits |
---|
React is proposing a new [https://github.com/reactjs/rfcs/pull/2](Context API). The API encourages composing. This utility component helps keep your code clean when your component will be rendering multiple Context Providers and Consumers.
install --save react-context-composor
rt React, { Component } from 'react'
rt ContextComposer from 'react-context-composer';
rt createReactContext, { type Context } from 'create-react-context';
Theme = 'light' | 'dark';
Language = 'en';
ass a default theme to ensure type correctness
t ThemeContext: Context<Theme> = createReactContext('light');
t LanguageContext: Context<Language> = createReactContext('en');
s ThemeToggler extends React.Component<
children: Node },
theme: Theme, language: Language }
ate = { theme: 'light', language: 'en' };
nder() {
return (
// Pass the current context value to the Provider's `value` prop.
// Changes are detected using strict comparison (Object.is)
<ContextComposer contexts={[
<ThemeContext.Provider value={this.state.theme}>
<LanguageContext.Provider value={this.state.language}>
]}>
<button
onClick={() => {
this.setState(state => ({
theme: state.theme === 'light' ? 'dark' : 'light'
}));
}}
>
Toggle theme
</button>
{this.props.children}
</ContextComposer>
);
tion Title({children}) {
turn (
<ContextComposer contexts={[ThemeContext, LanguageContext]}>
{(theme, language) => (
<h1 style={{ color: theme === 'light' ? '#000' : '#fff' }}>
{language}: {this.props.children}
</h1>
)}
</ContextComposer>
er(
hemeToggler>
<Title>Hi!</Title>
ThemeToggler>,
mNode
MIT © Blaine Kasten