FormidableLabs/react-context-composer

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

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

react-context-composor

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
install --save react-context-composor
Usage
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

License

MIT © Blaine Kasten


This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.