package
Polyfill for the proposed React context API
npm install create-react-contextGitHub-flavored package documentation.
Across all versions.
Download trend unavailable.
Runtime metadata.
Tagged topics.
Estimated unpacked size across 5 packages.
45.1 kB
Includes dependencies.
Polyfill for the proposed React context API
yarn add create-react-contextYou'll need to also have react and prop-types installed.
const Context = createReactContext(defaultValue);
// <Context.Provider value={providedValue}>{children}</Context.Provider>
// ...
// <Context.Consumer>{value => children}</Context.Consumer>// @flow
import React, { type Node } from 'react';
import createReactContext, { type Context } from 'create-react-context';
type Theme = 'light' | 'dark';
// Pass a default theme to ensure type correctness
const ThemeContext: Context<Theme> = createReactContext('light');
class ThemeToggler extends React.Component<
{ children: Node },
{ theme: Theme }
> {
state = { theme: 'light' };
render
This package only "ponyfills" the React.createContext API, not other
unrelated React 16+ APIs. If you are using a version of React <16, keep
in mind that you can only use features available in that version.
For example, you cannot pass children types aren't valid pre React 16:
<Context.Provider>
<div/>
<div/>
</Context.Provider>It 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>:
<Context.Provider>
<div>
<div/>
<div/>
</div>
</Context.Provider>