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
|
8 | yarn add create-react-context
|
9 | ```
|
10 |
|
11 | You'll need to also have `react` and `prop-types` installed.
|
12 |
|
13 | ## API
|
14 |
|
15 | ```js
|
16 | const 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
|
26 | import React from 'react';
|
27 | import createReactContext from 'create-react-context';
|
28 |
|
29 | type Theme = 'light' | 'dark';
|
30 | // Pass a default theme to ensure type correctness
|
31 | const ThemeContext: Context<Theme> = createReactContext('light');
|
32 |
|
33 | class 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 | Toggle theme
|
50 | </button>
|
51 | {this.props.children}
|
52 | </ThemeContext.Provider>
|
53 | );
|
54 | }
|
55 | }
|
56 |
|
57 | class Title extends React.Component<{ children: Node }> {
|
58 | render() {
|
59 | return (
|
60 | // The Consumer uses a render prop API. Avoids conflicts in the
|
61 | // props namespace.
|
62 | <ThemeContext.Consumer>
|
63 | {theme => (
|
64 | <h1 style={{ color: theme === 'light' ? '#000' : '#fff' }}>
|
65 | {this.props.children}
|
66 | </h1>
|
67 | )}
|
68 | </ThemeContext.Consumer>
|
69 | );
|
70 | }
|
71 | }
|
72 | ```
|