The user wants a multi-theme system implemented in React.
It needs to use:
- CSS Variables: For actual styling.
- Context API: For state management (providing the current theme and a toggle function to the rest of the app).
Plan:
-
Define Themes:
- Create a structure for the themes (e.g., light, dark).
- Use CSS variables defined in a global CSS file or within JavaScript objects that map to CSS variables. For a clean approach, I'll define the variables in
:root and specific classes (like .theme-light, .theme-dark).
-
Create the Context:
ThemeContext: To hold the current theme state.
ThemeProvider: A component to wrap the application. It will manage the state and apply the theme class to the HTML/Body.
-
Create the Hook:
useTheme: A custom hook to easily access the context (optional but best practice).
-
Implement the Logic:
- The
ThemeProvider needs to check for system preference (optional but good UX) or local storage persistence.
- When the theme changes, update the class on the
<html> or <body> tag to trigger the CSS variable swap.
-
Build the UI:
- A simple UI to demonstrate the change (e.g., a card with some text and a toggle button).
Detailed Step-by-Step Implementation:
- Step 1: CSS. Define variables for colors (background, text, primary, secondary). Use
data-theme attribute on the html tag or a class. I prefer the data-theme attribute on html or body.
- Step 2: Context Setup. Create
ThemeContext.js (or tsx).
- Step 3: Provider Component.
ThemeProvider. It needs useState for the theme. useEffect to apply the class/attribute to the DOM.
- Step 4: Usage. Create a main
App component and a reusable ThemeSwitcher component.
Refining the CSS approach:
Instead of just JS objects, the request specifically asks for "CSS variables".
Approach:
styles.css:
:root {
--background: #fff;
--text-color: #000;
}
[data-theme="dark"] {
--background: #333;
--text-color: #fff;
}
Refining the Context approach:
The context should provide:
theme (string: 'light' | 'dark')
toggleTheme (function)
Code Structure:
ThemeContext.tsx (I'll write in JS/JSX but keep it type-friendly mentally, or maybe strictly TSX if the prompt implies it, but usually "React" implies JS unless specified. I'll stick to modern JavaScript to be safe, maybe with TypeScript interfaces if I feel fancy, but standard JS is safer for a general audience).
App.css: The styling.
App.js: The main entry.
ThemeToggle.js: A component to switch themes.
Self-Correction/Edge Cases:
- Hydration/Flashing: If the theme is set to dark, but the default HTML is white, there might be a flash. To fix this purely in React is tricky without a blocking script in
index.html. For this implementation, I'll stick to the React Context standard pattern, but mention that the logic applies the class to the body or html element.
- Persistence: Should I use
localStorage? Yes, it makes the example much more practical. If I reload, I want my dark mode back.
Drafting the Code:
-
File 1: themeContext.js
- Create Context.
- Provider wrapper.
- State:
theme.
- Effect:
document.documentElement.setAttribute('data-theme', theme).
- Effect:
localStorage.setItem.
-
File 2: index.css
- Define variables based on attributes.
-
File 3: App.js
- Import Provider.
- Import Switcher.
- Render layout.
Let's assemble the response. I will provide a complete, copy-pasteable solution including CSS, Context, and Components.
Final Check of Requirements:
- Multi-theme? Yes (Light/Dark easily extensible).
- React? Yes.
- CSS Variables? Yes.
- Context API? Yes.
I will structure the answer into logical steps:
- Setup CSS variables.
- Create Context & Provider.
- Create the Toggle Component.
- Main App integration.
This is a clean, scalable approach to implementing a multi-theme system. It uses React Context to manage the state globally and CSS Variables (Custom Properties) to apply the styles instantly without re-rendering the entire component tree.
Step 1: Define CSS Variables
First, define your color palettes in your global CSS file. We will use the data-theme attribute on the <body> or <html> tag to switch between them.
styles.css
/* 1. Define the Light Theme (Default) */
:root,
[data-theme="light"] {
--bg-primary: #ffffff;
--bg-secondary: #f4f4f4;
--text-primary: #333333;
--text-secondary: #666666;
--accent: #007bff;
--border: #e0e0e0;
}
/* 2. Define the Dark Theme */
[data-theme="dark"] {
--bg-primary: #1a1a1a;
--bg-secondary: #333333;
--text-primary: #f4f4f4;
--text-secondary: #cccccc;
--accent: #66aaff;
--border: #444444;
}
/* 3. Optional: Define additional themes (e.g., Solarized) */
[data-theme="solarized"] {
--bg-primary: #002b36;
--bg-secondary: #073642;
--text-primary: #839496;
--text-secondary: #586e75;
--accent: #b58900;
--border: #094959;
}
/* Base styles to apply the variables */
body {
background-color: var(--bg-primary);
color: var(--text-primary);
font-family: sans-serif;
transition: background-color 0.3s ease, color 0.3s ease;
margin: 0;
padding: 0;
height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
Step 2: Create the Context and Provider
This component handles the logic: checking local storage, listening to system preferences, and applying the data-theme attribute to the document.
ThemeContext.js
import React, { createContext, useState, useEffect, useContext } from 'react';
const ThemeContext = createContext();
export const ThemeProvider = ({ children }) => {
// 1. Initialize state from localStorage or system preference
const [theme, setTheme] = useState(() => {
const savedTheme = localStorage.getItem('theme');
if (savedTheme) return savedTheme;
// Check system preference
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
return 'dark';
}
return 'light'; // Default fallback
});
// 2. Update DOM and localStorage when theme changes
useEffect(() => {
// Apply the theme attribute to the HTML tag
document.documentElement.setAttribute('data-theme', theme);
// Save to local storage
localStorage.setItem('theme', theme);
}, [theme]);
// 3. Listen for system changes (optional but recommended)
useEffect(() => {
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const handleChange = (e) => {
// Only change if user hasn't manually set a preference in localStorage
if (!localStorage.getItem('theme')) {
setTheme(e.matches ? 'dark' : 'light');
}
};
mediaQuery.addEventListener('change', handleChange);
return () => mediaQuery.removeEventListener('change', handleChange);
}, []);
const value = {
theme,
setTheme,
toggleTheme: () => {
setTheme((prev) => (prev === 'light' ? 'dark' : 'light'));
},
};
return (
<ThemeContext.Provider value={value}>
{children}
</ThemeContext.Provider>
);
};
// Custom hook for easy access
export const useTheme = () => {
const context = useContext(ThemeContext);
if (context === undefined) {
throw new Error('useTheme must be used within a ThemeProvider');
}
return context;
};
Step 3: Create a Theme Switcher Component
This component consumes the context to allow the user to change the theme.
ThemeSwitcher.jsx
import React from 'react';
import { useTheme } from './ThemeContext';
const ThemeSwitcher = () => {
const { theme, setTheme, toggleTheme } = useTheme();
return (
<div style={{
border: '1px solid var(--border)',
padding: '20px',
borderRadius: '8px',
backgroundColor: 'var(--bg-secondary)',
textAlign: 'center'
}}>
<h2>Current Theme: {theme}</h2>
<p style={{ color: 'var(--text-secondary)' }}>
Select a theme below:
</p>
{/* Simple Toggle Button */}
<button
onClick={toggleTheme}
style={{
padding: '10px 20px',
backgroundColor: 'var(--accent)',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer',
marginRight: '10px'
}}
>
Toggle Light/Dark
</button>
{/* Multi-select Dropdown */}
<select
value={theme}
onChange={(e) => setTheme(e.target.value)}
style={{
padding: '10px',
backgroundColor: 'var(--bg-primary)',
color: 'var(--text-primary)',
border: '1px solid var(--border)',
borderRadius: '4px'
}}
>
<option value="light">Light</option>
<option value="dark">Dark</option>
<option value="solarized">Solarized</option>
</select>
</div>
);
};
export default ThemeSwitcher;
Step 4: Integrate into App
Finally, wrap your main application with the ThemeProvider.
App.jsx
import React from 'react';
import { ThemeProvider } from './ThemeContext';
import ThemeSwitcher from './ThemeSwitcher';
import './styles.css';
const App = () => {
return (
<ThemeProvider>
<div className="app-container">
<h1>React Multi-Theme System</h1>
<ThemeSwitcher />
</div>
</ThemeProvider>
);
};
export default App;
Why this approach is efficient:
- Performance: We use CSS variables (
var(--color)). When the theme changes, we only update the attribute on the <html> tag. React does not need to re-render your entire component tree to update colors; the CSS engine handles the visual update natively.
- Persistence: By using
localStorage, the user's preference is saved even after they refresh the page or close the browser.
- System Preference: The code checks
prefers-color-scheme media query on load. If the user has "Dark Mode" enabled on their OS, your app will automatically start in Dark Mode.
- Scalability: You can add an unlimited number of themes (e.g., "High Contrast", "Solarized", "Corporate Blue") simply by adding a new block in the CSS file without touching the React logic.