React: Creating Dark Mode is extremely simple … of course if you like either too free or are afraid of eye pain.

Tram Ho

By 2020, when Facebook comes with Dark Mode, there’s no reason you don’t add a bit of dark to your site to increase the user experience a bit.

The better if you are a React developer, you can apply some simple steps below, the time is not too much but the effect will probably be quite good. If you understand this idea, you can convert it to Vuejs or JQuery project.


Let’s start a simple step with CSS first, you need to determine what Dark Mode needs to do, for me, it just needs to turn the bright white components of the website into dark colors such as the background and for example. contrast the dark content to a brighter color to stand out more on dark backgrounds, such as text, icons, borders, etc. depending on your senses.

And to do that, I will create 2 CSS files corresponding to 2 themes, dark and light



Here I use 2 variables –color and –background-color , for you who do not know, the declaration with the first 2 dashes in CSS is considered variable declaration, and this variable you Can be used to style web pages.

And as seen, I will use these 2 variables to define the background and the lines of text throughout the site, if the theme is dark then set the background a bit dark, the text will be bright white and vice versa.


Add a Component

Now the CSS is all that, ez too. Now to the main processing, you create a component named ToggleDarkMode , we will add a bit of code to index.js as follows:


Here I use localStorage to save the theme’s state right in the user’s browser, every time I reload the website I will check this status to see if this person has enabled dark mode and at the same time assign. This state enters the data-theme attribute.

If you do not remember, you can turn on the CSS section, this attribute will be used as a selector to determine if we will use dark or light styles.

And I have a small checkbox that will be checked if the user is using a dark theme, now we will add the processing code to use this checkbox as a toggle for dark mode here.


This part is too easy, add an onChange event and in this event we will check what the current theme is, if it is light then we will change it to dark, and vice versa.

And finally the result:

Pretty simple, but surprisingly effective. You can define other color components at will, playing 7 RGB colors is always okay

Thanks for watching the article!

Share the news now

Source : Viblo