Tailwind CSS: Dark and Light Theme

 Tailwind CSS: Dark and Light Theme 

I am using Tailwindcss in my react app. One of the requirement was to provide light and dark theme for the web app. This can be achieved easily with Tailwind.

1. Specify colours and styles for light and dark theme. For light theme just use class-name as it is and for  dark theme, use dark:class-name.

eg: bg-white dark:bg-gray-700


Switch between white and dark theme

To switch between the themes, there are many methods. I chose using class. Using class, need to mention darkMode: "class" in tailwind.config.js.

/** @type {import('tailwindcss').Config} */
module.exports = {
darkMode: "class",
theme: {
extend: {},
},
plugins: [],
content: ["./src/**/*.{js,jsx,ts,tsx,html}", "./public/index.html"],
};

Then we can add a button, on click add/remove class-name "dark" to/from <html> to toggle between dark between light theme.

document.documentElement.classList.toggle("dark");

or 

document.documentElement.classList.add("dark");
document.documentElement.classList.remove("dark");



Note: To keep the theme selection, we can store the value to localstorage and retrieve it on  load for better user experience.


Reference: https://tailwindcss.com/docs/dark-mode



No comments:

Post a Comment