This package has been deprecated

Author message:

This package aimed to simplify a use-case that luckily didn't become very popular, that is, using many contexts in a single app. If you are using many contexts, try using the react hook useContext to simplify your render trees.

react-context-composer

0.0.4 • Public • Published

react-context-composer

React 16.3 shipped a new Context API. The API encourages composition. This utility component helps keep your code clean when your component will be rendering multiple Context Providers and Consumers.

Install

npm install --save react-context-composer

Usage

import React, { Component } from 'react'
import ContextComposer from 'react-context-composer';
import createReactContext, { type Context } from 'create-react-context';
 
type Theme = 'light' | 'dark';
type Language = 'en';
 
// Pass a default theme to ensure type correctness
const ThemeContext: Context<Theme= createReactContext('light');
const LanguageContext: Context<Language= createReactContext('en');
 
class ThemeToggler extends React.Component<
  { children: Node },
  { theme: Theme, language: Language }
> {
  state = { theme: 'light', language: 'en' };
  render() {
    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>
    );
  }
}
 
function Title({children}) {
  return (
    <ContextComposer contexts={[ThemeContext, LanguageContext]}>
      {(theme, language) => (
        <h1 style={{ color: theme === 'light' ? '#000' : '#fff' }}>
          {language}: {children}
        </h1>
      )}
    </ContextComposer>
  );
}
 
render(
  <ThemeToggler>
    <Title>Hi!</Title>
  </ThemeToggler>,
  domNode
);

License

MIT © Blaine Kasten

Readme

Keywords

none

Package Sidebar

Install

npm i react-context-composer

Weekly Downloads

124

Version

0.0.4

License

MIT

Unpacked Size

8.11 kB

Total Files

5

Last publish

Collaborators

  • blainekasten