mini-create-react-context
(A smaller) Polyfill for the React context API
Install
npm install mini-create-react-context
You'll need to also have react
and prop-types
installed.
API
const Context = ;/* <Context.Provider value={providedValue}> {children} </Context.Provider> ... <Context.Consumer> {value => children} </Context.Consumer>*/
Example
// @flow;; type Theme = 'light' | 'dark';// Pass a default theme to ensure type correctnessconst ThemeContext: Context<Theme> = ; Component< children: Node theme: Theme > state = theme: 'light' ; { return // Pass the current context value to the Provider's `value` prop. // Changes are detected using strict comparison (Object.is) <ThemeContextProvider value=thisstatetheme> <button onClick= { this; } > Toggle theme </button> thispropschildren </ThemeContextProvider> ; } Component< children: Node > { return // The Consumer uses a render prop API. Avoids conflicts in the // props namespace. <ThemeContextConsumer> <h1 style= color: theme === 'light' ? '#000' : '#fff' > thispropschildren </h1> </ThemeContextConsumer> ; }
Compatibility
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:
<ContextProvider> <div/> <div/></ContextProvider>
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>
:
<ContextProvider> <div> <div/> <div/> </div></ContextProvider>
Size difference to the original:
original | mini | |
---|---|---|
install size | 50 kB | 140 kB |
minified | 3.3 kB | 2.3kB |
minzip | 1.3 kB | 1.0kB |