Ask any question about Web Development here... and get an instant response.
Post this Question & Answer:
How can I implement dark mode toggle in a React application using CSS variables?
Asked on Jun 01, 2026
Answer
To implement a dark mode toggle in a React application using CSS variables, you can leverage React's state management to toggle between light and dark themes. CSS variables allow you to define theme colors that can be easily switched in your stylesheets.
<!-- BEGIN COPY / PASTE -->
// App.js
import React, { useState } from 'react';
import './App.css';
function App() {
const [darkMode, setDarkMode] = useState(false);
const toggleDarkMode = () => {
setDarkMode(!darkMode);
document.documentElement.setAttribute('data-theme', darkMode ? 'light' : 'dark');
};
return (
<div className="App">
<button onClick={toggleDarkMode}>
Toggle Dark Mode
</button>
</div>
);
}
export default App;
/* App.css */
:root {
--background-color: white;
--text-color: black;
}
[data-theme="dark"] {
--background-color: black;
--text-color: white;
}
.App {
background-color: var(--background-color);
color: var(--text-color);
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
<!-- END COPY / PASTE -->Additional Comment:
- Use `document.documentElement.setAttribute` to set a `data-theme` attribute on the `` element, which allows CSS to apply different styles based on the theme.
- CSS variables defined in `:root` can be overridden by setting them in `[data-theme="dark"]`.
- Ensure that your CSS variables cover all necessary UI elements for a complete theme switch.
- Consider using localStorage to persist the user's theme preference across sessions.
Recommended Links:
