react-merged-context
A simple library for creating a context provider that merges together the context values throughtout the React tree.
Check it out in action at react-merged-context.netlify.app.
Installation
This package lives in npm. To install the latest stable version, run the following command:
npm install react-merged-context
Or if you're using yarn:
yarn add react-merged-context
Usage
You can create a merged context provider by passing your context to the createMergedProvider
method.
This will return a "merged context provider" which you can use
;; ; .../MyContextProvider;
Getting the value
Since createMergedProvider
just creates a "Provider" component, you can retrieve the value from the context using the normal methods - either through Context.Consumer
or useContext
.
Objects
Merged context providers can be used to apply a diff to the context.
;; ; MyContext.Consumer /MyContext.Consumer/MyContextProvider;
Arrays
Merged context providers can also be used to concat arrays.
;; ; MyContext.Consumer /MyContext.Consumer/MyContextProvider;
Resetting with React context providers
You can use normal context providers to reset the value of the context.
;; ; MyContextProvider value= MyContext.Consumer /MyContext.Consumer /MyContextProvider;/MyContext.Provider
Example
You can view the example live at react-merged-context.netlify.app.
To run the example locally:
- navigate to
example/
- install the dependencies by running
yarn
- run
yarn start
to start the dev server - navigate to
localhost:1234
License
MIT.