DEV Community

Cover image for DarkMode in TailWind
Shashank sharma
Shashank sharma

Posted on

DarkMode in TailWind

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)
2.Toggle button
3.Toggle Theme (Functionality)
4.What changes can we make to className for darkmode
5.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',
  // ...
}
Enter fullscreen mode Exit fullscreen mode

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.👍

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>
Enter fullscreen mode Exit fullscreen mode

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.

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

The button will look like this ...

Image description

Toggle Theme (Functionality)

Here, you are required to use useState hooks from react. 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'
    }
  }
Enter fullscreen mode Exit fullscreen mode

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

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

Image description

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

localStorage ,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
rescue
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
    )
}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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

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;
Enter fullscreen mode Exit fullscreen mode

Dark Mode)

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/
And can also refer to the code in my Github repo

Let me know if there is a better approach. For now this works. Refer the tailwind docs for more info. TailwindCSS

Top comments (2)

Collapse
 
lukasw12v profile image
lukas

Good article and good work!!
But a lot of text for a simple darkmode with tailwind :D

Collapse
 
shashannkbawa profile image
Shashank sharma

can't help... I got carried away😂