UNPKG

2.5 kBMarkdownView Raw
1# create-react-context
2
3> Polyfill for the [proposed React context API](https://github.com/reactjs/rfcs/pull/2)
4
5## Install
6
7```sh
8yarn add create-react-context
9```
10
11You'll need to also have `react` and `prop-types` installed.
12
13## API
14
15```js
16const Context = createReactContext(defaultValue);
17// <Context.Provider value={providedValue}>{children}</Context.Provider>
18// ...
19// <Context.Consumer>{value => children}</Context.Consumer>
20```
21
22## Example
23
24```js
25// @flow
26import React, { type Node } from 'react';
27import createReactContext, { type Context } from 'create-react-context';
28
29type Theme = 'light' | 'dark';
30// Pass a default theme to ensure type correctness
31const ThemeContext: Context<Theme> = createReactContext('light');
32
33class ThemeToggler extends React.Component<
34 { children: Node },
35 { theme: Theme }
36> {
37 state = { theme: 'light' };
38 render() {
39 return (
40 // Pass the current context value to the Provider's `value` prop.
41 // Changes are detected using strict comparison (Object.is)
42 <ThemeContext.Provider value={this.state.theme}>
43 <button
44 onClick={() => {
45 this.setState(state => ({
46 theme: state.theme === 'light' ? 'dark' : 'light'
47 }));
48 }}
49 >
50 Toggle theme
51 </button>
52 {this.props.children}
53 </ThemeContext.Provider>
54 );
55 }
56}
57
58class Title extends React.Component<{ children: Node }> {
59 render() {
60 return (
61 // The Consumer uses a render prop API. Avoids conflicts in the
62 // props namespace.
63 <ThemeContext.Consumer>
64 {theme => (
65 <h1 style={{ color: theme === 'light' ? '#000' : '#fff' }}>
66 {this.props.children}
67 </h1>
68 )}
69 </ThemeContext.Consumer>
70 );
71 }
72}
73```
74
75## Compatibility
76
77This package only "ponyfills" the `React.createContext` API, not other
78unrelated React 16+ APIs. If you are using a version of React <16, keep
79in mind that you can only use features available in that version.
80
81For example, you cannot pass children types aren't valid pre React 16:
82
83```js
84<Context.Provider>
85 <div/>
86 <div/>
87</Context.Provider>
88```
89
90It will throw `A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.` because `<Context.Provider>` can only receive a single child element. To fix the error just wrap everyting in a single `<div>`:
91
92```js
93<Context.Provider>
94 <div>
95 <div/>
96 <div/>
97 </div>
98</Context.Provider>
99```