DarkMode in TailWind
Tags: javascript, tailwindcss, darkmode, react
Published: 2022-01-24 12:00:18

So I am writing this post as I have faced some problems while using dark mode in my website with the help of TailwindCSS.

I wanted to toggle between light mode and dark mode manually.

So please allow me to tell the whole story behind creation of simple Dark mode.

###List of Contents

1.[Prerequiste (things that you have to do before using darkmode)](#prerequisite-things-that-you-have-to-do-before-using-darkmode)
2.[Toggle button](#toggle-button)
3.[Toggle Theme (Functionality)](#toggle-theme-functionality)
4.[What changes can we make to `className` for darkmode](#what-changes-can-we-make-to-raw-classname-endraw-for-darkmode)
5.[Temprory Functioning](#temprory-functioning)


##Prerequisite (things that you have to do before using darkmode)


As it has also been stated in the Tailwind documentaion of darkmode . Add `darkMode: 'class',` in your tailwind.config.js like this below.

```
module.exports = {
  darkMode: 'class',
  // ...
}
```
It basically add `class=" "` into your HTML.

_Bro, but why ain't we using `media` instead of `class`?_ .
 The thing is `media` will take your OS color scheme into consideration and `class` will let you add it manually. So,  that's the theory behind it.:thumbsup:


## Toggle button

It basically makes a button that listens to a `onClick` function on clicking it.


```
<div className='flex items-center justify-center inline-flex '>
      <label className='pt-0 pb-1 w-10 mb-6 ' >
             <div className='w-12 h-5 border-2 justify-center 
                             items-center rounded-lg bg-#172d42 
                             mt-1 absolute' type='checkbox' />
             <input onClick={theme} className='bg-[#ffffff] w-7 h-7
                                              flex justify-center items-center
                                              duration-500 checked:translate-x-6
                                              checked:bg-black appearance-none
                                              rounded-full absolute ease-in-out' type='checkbox' >
             </input>
      </label>
</div>
```


> You can change the `className` values according to your CSS. 


So here, `checked` means that, when the checkbox input is checked, it will `translate-x-6` translate in x-axis i.e. toward right. And the rest is basic tailwind CSS. You can search the meaning of the values of `className` in their [website](https://tailwindcss.com/).


**Main Thing** We have passed `theme` to the `onClick` function. About which, we will talk later. 
 

The button will look like this ...

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u23xcoxo0hly25qngyxi.png)


##Toggle Theme (Functionality)

Here, you are required to use `useState` hooks from [react](https://reactjs.org/docs/hooks-intro.html). But first, let me introduce you to my code then we will talk about it.


```
const [theme, setTheme] = useState('light');

const toggleTheme = () => {
    
    if (theme === 'dark') {
      document.documentElement.classList.remove('dark')
      setTheme('light')
      localStorage.theme = 'dark'
    } else {
      document.documentElement.classList.add('dark')
      setTheme('dark')
      localStorage.theme = 'light'
    }
  }
```


Initially, I have set the `theme` state to 'light'. I wanted that user must first see the light mode and then toggle to the dark mode. But, if you want the user to see the dark mode first then set it to 'dark'.
 `const [theme, setTheme] = useState('dark');`


I used normal if else statement, for beginners understanding. You can also use ternary operator {  ? <> : <> } .


> You have plenty of options with JavaScript. That's the beauty of it. 


_But dude, tell us more, what does_ `document.documentElement.classList.add('dark')` _do_.
 It basically adds `class="dark"` into your HTML.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ezbp8bjcp442fon7m4xi.png)


 And `document.documentElement.classList.remove('dark')` will make it back to the normal.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/imt4fyoxqhlpsftyq8jm.png)


So, next comes the `localStorage.theme = 'dark'`.


>[localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API) ,an API that allows you to store key-value pairs of data that persist with page reloads as well as when the browser window is closed and reopened.


You can read the official documentation of `localStorage` from Mozilla. Basically, it will store the value of the `theme` in your browser for local reference.

**The main monopoly behind this `toggleTheme` is**
 The user clicks on the button. That will invoke `toggleTheme` and it will check, if the theme is dark, then remove 'dark' from HTML and `setTheme` to 'light' and set `localStorage.theme` to light.
And, if user again clicks on the button, then it will again invoke `toggleTheme` and this time the theme is set to 'light' then the else part will execute. That will add 'dark' to HTML and `setTheme` to 'dark' and set `localStorage.theme` to dark.


So, now I think you would be comfortable with the functioning behind `toggleTheme`.


_Then, where to put this_ `toggleTheme` _function?_ React comes to the rescue 
![rescue](https://media.giphy.com/media/iJHzVfDR5WXPVgZJyS/giphy.gif)
![rescue](https://media.giphy.com/media/f8VxRaHxaTqkOUgywz/giphy.gif)
I wrote this in my `App.jsx`. So that, it would be easy to pass the props to the other components.


You have to pass the theme into your components. I did it like this

`<Navbar theme={toggleTheme} />` in my App.jsx

My Navbas.jsx 

```
const Navbar = ({ theme }) => {
    return(
        <>
        </>
        //rest of the code
    )
}
```


and used it in my `onClick` function, about that I have mentioned earlier.
`<input onClick={theme} className='bg-[#ffffff]' type='checkbox' >`


##What changes can we make to `className` for darkmode
If you wanted to change the text, background and other values, with the help of darkmode of TailwindCSS, you can do it simply by adding `dark:text-white` in your `className`.


```
<div className='text-black dark:text-white'>

</div>
```


And that's it folks, you will now be able to see the button and toggle between the light theme and dark theme.:tada:


##Temprory Functioning


A basic illustration of dark mode with ReactJS.


```
import React, { useState } from 'react';

const DarkMode = () => {

    const [theme, setTheme] = useState('light');

    const toggleTheme = () => {

        if (theme === 'dark') {
            document.documentElement.classList.remove('dark')
            setTheme('light')
            localStorage.theme = 'dark'
        } else {
            document.documentElement.classList.add('dark')
            setTheme('dark')
            localStorage.theme = 'light'
        }
    }
    return <div className='mt-7 max-w-full m-h-full bg-black dark:bg-slate-700 flex items-center justify-center  '>
        <label className='pt-0 pb-1 w-10 mb-6 ' >

            <div className='w-12 h-5 border-2 justify-center items-center rounded-lg bg-#172d42 mt-1 absolute' type='checkbox' />
            <input onClick={toggleTheme} className='bg-yellow-200 w-7 h-7  flex justify-center items-center duration-500 checked:translate-x-6 checked:bg-black appearance-none rounded-full absolute ease-in-out' type='checkbox' >
            </input>


        </label>
        <h1 className='mx-5 text-white dark:text-red-900'>Heyyy there</h1>

    </div>
        ;
};

export default DarkMode;
```


![Dark Mode](https://play.vidyard.com/zvU5319QsCAUaWshwh9kqD.jpg))



If you wanted to see the functioning of dark and light mode, then you can check this website [https://shashannkbawa.github.io/Shanks-Web3.0/](https://shashannkbawa.github.io/Shanks-Web3.0/)
And can also refer to the code in my [Github repo](https://github.com/shashannkbawa/Shanks-Web3.0)



>Let me know if there is a better approach. For now this works. Refer the tailwind docs for more info. [TailwindCSS](https://tailwindcss.com/)