Theme toggle using Tailwind CSS in just 3 steps

shrey vijayvargiya - Apr 11 '23 - - Dev Community

Under the Hood

Let's begin, I want to add a dark/white theme to my website what should I do?

That is how the story begins literally theme toggle on the website

So most of the websites use Tailwind CSS in React so let’s begin with that only.

Step 1

Append the theme classname to the root element of the application.

Basically, the root div element of the application should contain the classname as the dark when a theme is dark and white when a theme is white.

import React from "react";

const App = () => (
 <div classname={`${theme}`}>
  <div> Home </div>
 </div>
);

export default App;
Enter fullscreen mode Exit fullscreen mode

Step 2

Store the current theme in local storage.

Add the dark theme CSS to the UI components as shown in the code example below.

import React from "react";

const App = () => {

 const theme = window.localstorage.get("theme");
 // fetch theme from localstorage


 return (
  <div classname={`${theme}`}>
   <div> <button className="dark:bg-gray-800 bg-gray-100"></button></div>
    // append the dark theme and work is done 
  </div>
)};

export default App;
Enter fullscreen mode Exit fullscreen mode

Step 3

Enable dark theme in Tailwind configuration

Go to the tailwind.config.js file in the root directory, if not available please create one with the same name.

// append the below line or out it after purge key
darkMode: "class", // or 'media' or 'class',
Enter fullscreen mode Exit fullscreen mode

This will basically instruct tailwind to append the given class CSS present in the root of the element.

Tailwind CSS will provide a manual theme or by default white theme if the ‘media’ value is provided.

Conclusion

That’s it two steps and you can theme toggle in tailwind css application, in fact in all the applications.

Below is the Github repository as the code sample, enjoy it.

Code sample

Demo

Until next time, have a good day, people
Shrey
iHateReading

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .