we are going to make a dark mode with a smooth effect.
Main idea
The idea is; we are going to have a state
const [theme, setTheme] = useState(true);
and a variable named which is going to have the color of the theme
const color = theme ? "White" : "Dark";
we are going to put the color variable in the CSS classes that need to know in which mode is the application
className={"SomeClass-${color}"}
Then we create a class for each color with this line at the beginning transition: all 0.25s linear;
.SomeClass-White {
transition: all 0.25s linear;
background-color: white;
}
.SomeClass-Dark {
transition: all 0.25s linear;
background-color: black;
}
Tutorial
First of all, we have to create a react app, for practical purposes we are going to use the command:
npx create-react-app darkmode
in the src folder, we just need the App.js, App.css, index.css, and index.js files, the other ones you can delete or just omit.
in App.js we have this code
import React, { useState } from "react";
import "./App.css";
function App() {
const [theme, setTheme] = useState(true);
const color = theme ? "White" : "Dark";
if (theme) {
document.body.classList.remove("DarkMode");
document.body.classList.add("WhiteMode");
} else {
document.body.classList.remove("WhiteMode");
document.body.classList.add("DarkMode");
}
return (
<div>
<h1 className={`App-h1-${color}`}>Dark mode</h1>
<button onClick={() => setTheme(!theme)}>Change theme</button>
</div>
);
}
export default App;
We have a state named theme, and a variable named color which has the word White or Dark; That variable we are going to use in each class that needs to know the state of the application
the conditional if
is used to change the body class.
Now we add this code to index.css (classes for the body tag)
.DarkMode {
transition: all 0.25s linear;
background-color: black;
}
.WhiteMode {
transition: all 0.25s linear;
background-color: white;
}
Then we add this code to App.css
.App-h1-White {
transition: all 0.25s linear;
color: black;
}
.App-h1-Dark {
transition: all 0.25s linear;
color: white;
}
Here we can see the different classes for dark mode and white mode, the line of code that makes the smooth animations is transition: all 0.25s linear;
And that's it, now to have the theme state accessible to all your components you can pass it as a prop or create a context.
You can see a website that uses this strategy for dark mode website
and the code of this website is here Github repo
Top comments (3)
Nothing I love more than a good dark mode! lol
any great way inheritance the transition in CSS avoid many duplicates?
I haven't thought of a good one, but you can try with the
inherit
value in transition property