You saw in the last three exercises how Contexts can share data in an area of a React application. Now we’re going to show the common coding patterns many React developers use with Contexts and their .Provider
components.
To start, it’s common for React applications to create a “wrapper” component around a .Provider
component. The wrapper component can provide a value of its choosing, often one of its props or a string literal, to the .Provider
component.
For example, here’s a ThemedMessage
component that returns the ThemeContext.Provider
component wrapped around any children
components it receives. ThemedMessage
also assigns a value using a theme
prop:
const ThemeContext = React.createContext(); const ThemedMessage = ({ children, theme }) => { return ( <ThemeContext.Provider value={theme}> This content is in {theme} mode! {children} </ThemeContext.Provider> ); };
Wrapper components like ThemedMessage
can then be used in place of a .Provider
component to wrap children:
// Renders: // This content is in dark mode! Hooray! const MyComponent = () => { return ( <ThemedMessage theme="dark"> Hooray! </ThemedMessage> ) };
In this exercise, you’ll prepare the application for more changes later on by setting up a dedicated wrapper component for the ThemeContext
Context. We’ll refactor ThemeContext
so that later it can provide more than just the theme
string to its consumers.
Instructions
In the workspace’s ThemeContext.js
file, create and export a new component named ThemeArea
. It should take in two props: children
and initialTheme
.
For the ThemeArea
component’s returned value, return the children
prop wrapped in a ThemeContext.Provider
component. Use the initialTheme
prop as the value for the ThemeContext.Provider
.
Now that the ThemeArea
component acts as a wrapper around MyContext.Provider
, replace any calls to MyContext.Provider
in ContactsApp.js
with ThemeArea
. Make sure to use the initialTheme
prop rather than the value
prop of the .Provider
. This shouldn’t change the behavior of your application at all – it’s only setting it up to be made more dynamic in the next exercise!