Many apps are providing night/dark mode now as it is more comforting to the eyes and improves visibility so I wanted to make a simple react app and implement the night mode. Below here is shown what I did to achieve it.
First I created a button to toggle on/off night mode.
<button
className="theme-btn"
onClick={() => {}}
/>
and styled it like this
.theme-btn {
border: none;
width: 30px;
height: 30px;
border-radius: 15px;
border-width: 1px;
background: pink;
border-color: pink;
margin-right: 10px;
cursor: pointer;
}
Then I added some text and gave styles to it, my app component looked like this
return (
<div>
<div className="nav">
<button
className="theme-btn"
onClick={() => {}}
/>
</div>
<h1>
Dark Theme
</h1>
<h2>
Dark theme is so cool!
</h2>
</div>
);
.nav {
display: flex;
flex: 1;
flex-direction: "row";
align-items: center;
width: "100%";
height: 40px;
}
After that, I initialized the state using React Hooks with its initial value as false and toggled its value between true and false upon the dark mode button click.
const [isDarkTheme, setIsSetDarkTheme] = useState(false);
onClick method looks like this
onClick={() => {
setIsSetDarkTheme(!isDarkTheme);
}}
Now I just applied conditional styling to text like this
style = {isDarkTheme ? { color: "white" } : { color: "black" }}
I also initialized another state that will show the text of the button according to the mode selected.
Whole component looked like this
export default function App() {
const [isDarkTheme, setIsSetDarkTheme] = useState(false);
const [themeText, setThemeText] = useState("Go Dark");
return (
<div
style={
isDarkTheme
? { backgroundColor: "black" }
: { backgroundColor: "white" }
}
>
<div className="nav">
<button
className="theme-btn"
onClick={() => {
isDarkTheme ? setThemeText("Go Dark") : setThemeText("Go Light");
setIsSetDarkTheme(!isDarkTheme);
}}
/>
<p style={isDarkTheme ? { color: "white" } : { color: "black" }}>
{themeText}
</p>
</div>
<h1 style={isDarkTheme ? { color: "white" } : { color: "black" }}>
Dark Theme
</h1>
<h2 style={isDarkTheme ? { color: "white" } : { color: "black" }}>
Dark theme is so cool!
</h2>
</div>
);
}
You can keep isDarkTheme
state in redux to use it in multiple components across the app, you can also create dark-theme
and light-theme
styling classes and use it across the app.
Try running the demo of Night Mode here