1- // Create a theme context, defaulting to light theme
2- // highlight-next-line
1+ // highlight-range{1-4}
2+ // Context lets us pass a value deep into the component tree
3+ // without explicitly threading it through every component.
4+ // Create a context for the current theme (with "light" as the default).
35const ThemeContext = React . createContext ( 'light' ) ;
46
5- function ThemedButton ( props ) {
6- // highlight-range{1,3-5}
7- // The ThemedButton receives the theme from context
8- return (
9- < ThemeContext . Consumer >
10- { theme => < Button { ...props } theme = { theme } /> }
11- </ ThemeContext . Consumer >
12- ) ;
7+ class App extends React . Component {
8+ render ( ) {
9+ // highlight-range{1-3,5}
10+ // Use a Provider to pass the current theme to the tree below.
11+ // Any component can read it, no matter how deep it is.
12+ // In this example, we're passing "dark" as the current value.
13+ return (
14+ < ThemeContext . Provider value = "dark" >
15+ < Toolbar />
16+ </ ThemeContext . Provider >
17+ ) ;
18+ }
1319}
1420
15- // An intermediate component
21+ // highlight-range{1,2}
22+ // A component in the middle doesn't have to
23+ // pass the theme down explicitly anymore.
1624function Toolbar ( props ) {
1725 return (
1826 < div >
@@ -21,13 +29,14 @@ function Toolbar(props) {
2129 ) ;
2230}
2331
24- class App extends React . Component {
25- render ( ) {
26- // highlight-range{2,4}
27- return (
28- < ThemeContext . Provider value = "dark" >
29- < Toolbar />
30- </ ThemeContext . Provider >
31- ) ;
32- }
32+ function ThemedButton ( props ) {
33+ // highlight-range{1-3,6}
34+ // Use a Consumer to read the current theme context.
35+ // React will find the closest theme Provider above and use its value.
36+ // In this example, the current theme is "dark".
37+ return (
38+ < ThemeContext . Consumer >
39+ { theme => < Button { ...props } theme = { theme } /> }
40+ </ ThemeContext . Consumer >
41+ ) ;
3342}
0 commit comments