Skip to content

Tired of nesting your context providers, try react-nest!

License

Notifications You must be signed in to change notification settings

reaktivo/react-nest

Repository files navigation

react-nest

Tired of nesting your context providers, try react-nest!

GitHub license npm version Build Status Coverage PRs Welcome

Installation

To install, you can use npm or yarn:

$ npm install react-nest
$ yarn add react-nest

😤 The problem

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>
  );
}

💡 The solution

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>
  );
}

📋 Copy/paste

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>
  );
}

License

react-nest is open source software licensed as MIT.

About

Tired of nesting your context providers, try react-nest!

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published