Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two providers in a React component

I'm looking to implement stripe elements in my React app and looks like there's a nice wrapper that I can use.

However, in the article, the author says we must use the StripeProvider and he implements it at the root App component level -- see https://github.com/stripe/react-stripe-elements#getting-started

I need to use my own provider to connect to my store. How do I use two providers in my component? I'm not even sure if this is a good idea.

My current render method looks like this:

render(
    <Provider store={store}>
        <App>
            <SomeComponentInMyApp />
        </App>
    </Provider>,
    document.getElementById('content-wrapper')
);

Would I wrap one provider around the other?

like image 359
Sam Avatar asked Jan 21 '18 05:01

Sam


People also ask

Can you have multiple providers React?

We can pass in anything we want to the value prop of the context provider component. So sharing multiple states with one provider is no problem.

What are providers in React?

Provider is the container for all React Spectrum applications. It defines the theme, locale, and other application level settings, and can also be used to provide common properties to a group of components.

Can we have multiple context in React?

Context does NOT have to be global to the whole app, but can be applied to one part of your tree. You can (and probably should) have multiple logically separated contexts in your app.


1 Answers

Yup, you should be able to wrap as many providers as you want:

render(
  <ProviderA whatever={3}>
    <ProviderB store={store}>
      <App>
        <SomeComponentInMyApp />
      </App>
    </ProviderB>
  <ProviderA>,
  document.getElementById('content-wrapper')
);

A provider is a Higher-Order Component that should just hook into React and provide additional capabilities (usually on the context) without altering anything or removing existing functionality.

That also means that the order of providers doesn't really matter unless for some reason providers depend on each other's existence.

Another example could be the ThemeProvider from styled-components.

You might run into a problem if you nest the same provider multiple times as they might potentially interfere with each other but in general a provider pattern is a common approach to decorate a react app with functionality available across the app without needing to pass that functionality to each component individually.

like image 108
nem035 Avatar answered Oct 03 '22 23:10

nem035