You’ve seen how React Context Providers can be used in multiple places in a React app. Here’s an brief example of a GreeterContext used to sets up different greetings for child components:
<GreeterContext.Provider value="Salut!"> <ChildComponent /> </GreeterContext.Provider> <GreeterContext.Provider value="Hallo!"> <ChildComponent /> </GreeterContext.Provider>
A Context Provider may be a child in the application tree underneath an earlier Context Provider. Components subscribing to a Context’s Provider will receive the value for the .Provider
component closest to them in the application tree. This pattern is sometimes referred to as “nesting”.
<GreeterContext.Provider value="Salut!"> <HighLevelComponent> {// GreeterContext's value is "Salut!" here} <GreeterContext.Provider value="Hallo!"> <LowLevelComponent /> {// GreeterContext's value is "Hallo!" here} </GreeterContext.Provider> </RootComponent> </GreeterContext.Provider>
In this example, we have two components that are used within the GreeterContext.Provider
: HighLevelComponent
and LowLevelComponent
. Each component will use the value of the nearest GreeterContext.Provider
. In this case, HighLevelComponent
will have the value "Salut!"
when using GreeterContext
while the LowLevelComponent
will have the value "Hallo!"
.
We’re going to use Context nesting to set up nested theming in our contacts management app:
- One root context around the entire application will set up a root theme for the entire application.
- A nested context in each section of contacts will override the root theme for their section’s contact items.
Instructions
Import ThemeArea
into index.js
and wrap the <ContactsApp />
with a ThemeArea
. Give it an initialTheme
prop value of "light"
.
Great! Now that ContactsApp
is inside a ThemeArea
, it can use the value of the ThemeContext
. Next, we’ll extract the theme inside ContactsApp
.
- Import
ThemeContext
and React’suseContext
intoContactsApp.js
. - Then, call
useContext()
to Retrieve thetheme
value in theContactsApp
component. - Finally, use
theme
to give the rendered<div>
aclassName
prop like so:
<div className={`theme-${theme}`}>
Since the theme is initially set to "light"
, the application should start off with the class "theme-light"
.
Let’s give users the option to change the root application theme as well. Import the ThemeSwitcher
component from ThemeSwitcher.js
into ContactsApp.js
and render it after the <h1>
heading.