Context & Patterns — Advanced React challenge.
Build a ThemeContext where ThemeProviders can be NESTED — a nested provider creates a genuinely independent scope, overriding the theme only for its own subtree, while everything outside it keeps reading the outer theme. Themed components must also apply real inline CSS matching the resolved theme.
Requirements
- ThemeProvider accepts a theme prop and provides { theme } via Context.
- useTheme() returns the nearest ThemeProvider's theme and throws if there's no ThemeProvider above the caller.
- Nesting a ThemeProvider inside another overrides the theme only within its own subtree — components outside the nested provider are unaffected.
- ThemedBox reads the resolved theme via useTheme() and applies real inline styles: light → white background, dark text; dark → dark background, white text.
- ThemedBox also carries a data-theme attribute matching the resolved theme.
- Sidebar wraps its own ThemedBox in a nested ThemeProvider forced to 'dark', regardless of the app's outer theme.
Signature
function ThemeProvider({ theme: "light" | "dark"; children: React.ReactNode }): JSX.Element
function useTheme(): { theme: "light" | "dark" }
function ThemedBox({ label: string }): JSX.ElementExample
<ThemeProvider theme="light">
<ThemedBox label="stays light" />
<ThemeProvider theme="dark">
<ThemedBox label="scoped dark" />
</ThemeProvider>
</ThemeProvider>
// first box: white background, dark text
// second box: dark background, white text — independent of the outer themeConstraints
- Do not use a single global theme variable outside React — the scoping must come from Context nesting itself.
- Use inline styles (style={{...}}) for the theme colors, not CSS classes.