Tired of nesting your context providers, try react-nest
!
To install, you can use npm or yarn:
$ npm install react-nest
$ yarn add react-nest
At one point in a complex application your root component might look like the following:
function App() {
return (
<AsyncComponentProvider asyncContext={asyncContext}>
<JobProvider jobContext={jobContext}>
<StaticRouter location={request.url}>
<Provider store={store}>
<IntlProvider>
<App />
</IntlProvider>
</Provider>
</StaticRouter>
</JobProvider>
</AsyncComponentProvider>
);
}
react-nest
helps you make your nested providers and consumers more readable and succinct by allowing you do the following:
import Nest from 'react-nest';
function App() {
return (
<Nest>
<AsyncComponentProvider asyncContext={asyncContext} />
<JobProvider jobContext={jobContext} />
<StaticRouter location={request.url} />
<Provider store={store} />
<IntlProvider />
<App />
</Nest>
);
}
react-nest, a library so small you might as well copy-and-paste it into your app:
function Nest(props) {
const children = React.Children.toArray(props.children).reverse();
return (
<React.Fragment>
{children.reduce(
(child, parent) =>
React.isValidElement(parent)
? React.cloneElement(parent, parent.props, child)
: child,
null
)}
}
</React.Fragment>
);
}
react-nest is open source software licensed as MIT.