Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 11, 2023 09:14 am GMT

Theme toggle using Tailwind CSS in just 3 steps

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 lets 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;

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;

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 keydarkMode: "class", // or 'media' or 'class',

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

Thats 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


Original Link: https://dev.to/shreyvijayvargiya/theme-toggle-using-tailwind-css-in-just-3-steps-1eij

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To