Skip to content
This repository was archived by the owner on Nov 23, 2021. It is now read-only.

Repository files navigation

mini-create-react-context

npm install sizenpm bundle sizenpm

(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

constContext=createReactContext(defaultValue);/*	<Context.Provider value={providedValue}> {children}	</Context.Provider>	...	<Context.Consumer> {value => children}	</Context.Consumer>*/

Example

// @flowimportReact,{typeNode}from'react';importcreateReactContext,{typeContext}from'mini-create-react-context';typeTheme='light'|'dark';// Pass a default theme to ensure type correctnessconstThemeContext: Context<Theme> = createReactContext('light');
class ThemeToggler extends React.Component<{children: Node},{theme: Theme}>{state={theme: 'light'};render(){return(// Pass the current context value to the Provider's `value` prop.// Changes are detected using strict comparison (Object.is)<ThemeContext.Providervalue={this.state.theme}><buttononClick={()=>{this.setState(state=>({theme: state.theme==='light' ? 'dark' : 'light'}));}}>
Toggle theme
</button>{this.props.children}</ThemeContext.Provider>);}}classTitleextendsReact.Component<{children: Node}>{render(){return(// The Consumer uses a render prop API. Avoids conflicts in the// props namespace.<ThemeContext.Consumer>{theme=>(<h1style={{color: theme==='light' ? '#000' : '#fff'}}>{this.props.children}</h1>)}</ThemeContext.Consumer>);}}

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:

<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>

Size difference to the original:

originalmini
install size50 kB140 kB
minified3.3 kB2.3kB
minzip1.3 kB1.0kB

About

(A smaller) polyfill for the react context API

Topics

Resources

Stars

Watchers

Forks

Releases

Packages

Used by

Contributors

Languages