Small and lightweight context consumer for your class-components
As any other npm package react-context-consumer
can be added to your project by following command:
npm i -S react-context-consumer
It requires any version of react with new context API support as peer dependency, so it should be installed as well.
npm i -S react
With new Context API to consume several contexts we need to put several context consumers in our component (one for each context):
import React, { Component } from 'react';
class MyComponent extends Component {
render() {
return (
<ThemeContext.Consumer>
{theme => (
<LocaleContext.Consumer>
{locale => (
<StorageContext.Consumer>
{storage => (
// render component using theme, locale and storage
)}
</StorageContext.Consumer>
)}
</LocaleContext.Consumer>
)}
</ThemeContext.Consumer>
);
}
}
react-context-consumer
helps to simplify render()
function in such situations. Just pass several contexts into contexts
prop and consume all of them at once:
import React, { Component } from 'react';
import ContextConsumer from 'react-context-consumer';
class MyComponent extends Component {
render() {
return (
<ContextConsumer contexts={[ ThemeContext, LocaleContext, StorageContext ]}>
{(theme, locale, storage) => {
// render component using theme, locale and storage
}}
</ContextConsumer>
);
}
}
I guess, it looks nicer =)
Let's imagine we already have a component using react context consumers and custom render prop with additional arguments like this one:
class CustomComponent extends React.Component {
...
renderComponent(someValue) {
return (
<ThemeContext.Consumer>
{theme => (
<LocaleContext.Consumer>
{
locale => this.renderComponentWithContext(theme, locale, someValue)
}
</LocaleContext.Consumer>
)}
</ThemeContext.Consumer>
)
}
renderComponentWithContext(theme, locale, someValue) {
...
}
}
You can now just pass all needed additional arguments using args
prop:
class CustomComponent extends React.Component {
...
renderComponent(someValue) {
return (
<ContextConsumer contexts={[ ThemeContext, LocaleContext ]} args={[ someValue ]}>
{this.renderComponentWithContext}
</ContextConsumer>
)
}
...
}