DEV Community

Cover image for How to add a dark mode to your React web app

How to add a dark mode to your React web app

Wachira on August 16, 2019

We are currently living in a dark mode in everything era. Most apps nowadays come with a switch either at the navbar or just somewhere around its s...
Collapse
 
chrisachard profile image
Chris Achard

Very nice! Great idea storing it in localstorage so it's the same when the user comes back the next time.

Also love the variables in CSS - I definitely didn't know that those were supported outside of scss, etc!

Collapse
 
wchr profile image
Wachira

Yes if you close that tab and come visit the link again it will still be the theme you last set

Collapse
 
andres profile image
Andrés Pérez • Edited

Pst, I gave it a spin and implemented it using hooks, here's the comparison gist.github.com/Oxyrus/b4edab0372b... (doesn't include the fancy toggle because I was lazy 😆)

Collapse
 
thgh profile image
Thomas Ghysels

Cool, I would have used useLocalState from the use-hooks package.

Collapse
 
wchr profile image
Wachira

Nice 💯

Collapse
 
arnu515 profile image
arnu515

You're writing longer, more complicated code. For example, instead of writing

checked: localStorage.getItem("theme") === "dark" ? true : false,

You can write:

checked: localStorage.getItem("theme") === "dark",

because localStorage.getItem("theme") === "dark" is a boolean and its value will be true or false.

Also, instead of writing

document.getElementsByTagName("HTML")[0]

You can write

document.querySelector("html")

and it will do the same thing.

There's nothing wrong with your code, but I'm just telling you how to make it more efficient

Collapse
 
andres profile image
Andrés Pérez

Question, what's the point of having a theme property inside your state? I don't see you using it anywhere.

Collapse
 
wchr profile image
Wachira

I kinda forgot to remove it. Before I was using the theme value to toggle the theme change

Collapse
 
aneudysamparo profile image
Aneudys Amparo

WOW 🤩 Simple and directly to the point!
Thank you for posting, I’ll use your guide as starting point.

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
wchr profile image
Wachira

Anytime