Nested providers

With React context, it is also possible to define multiple providers for the same context. Using this technique, we can override the context value in certain parts of our app. Let's consider the earlier example, and add a second header to it:

  1. Edit src/App.js, and add a second Header component:
const App = () => (
<ThemeContext.Provider value={{ primaryColor: 'coral' }}>
<Header text="Hello World" />
<Header text="This is a test" />
</ThemeContext.Provider>
)

export default App
  1. Now, define a second Provider component with a different primaryColor:
const App = () => (
<ThemeContext.Provider value={{ primaryColor: 'coral' }}>
<Header text="Hello World" />
<ThemeContext.Provider value={{ primaryColor: 'deepskyblue' }}>
<Header text="This is a test" />
</ThemeContext.Provider>
</ThemeContext.Provider>
)

export default App

If we open the app in our browser, the second header now has a different color from the first one:

Overriding context values with nested providers

As we can see, we can override React context values by defining providers. Providers can also be nested, therefore overriding the values of other providers that are higher up in the component tree.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.156.250