To enable the manual dark mode feature in your tailwindcss website first add darkMode: 'class'
in your tailwind.config.js file
jsmodule.exports = {
darkMode: "class",
...
}
Then we have to create a custom hook for getting the current theme and toggling the theme.
jsimport { useEffect, useState } from "react";
export const useTheme = () => {
const [mode, setMode] = useState("light");
function changeTheme() {
const html = document.documentElement;
if (mode == "light") {
html.classList.remove("light");
html.classList.add("dark");
setMode("dark");
localStorage.setItem("mode", "dark");
} else {
html.classList.remove("dark");
html.classList.add("light");
setMode("light");
localStorage.setItem("mode", "light");
}
}
useEffect(() => {
const currentMode = localStorage.getItem("mode") || "light";
document.documentElement.classList.add(currentMode);
setMode(currentMode);
}, []);
return { changeTheme, mode }
};
Finally, we can import the useTheme
hook in any of our components and bind the changeTheme function with a button or any element.
Whenever we call the changeTheme function it will change the website's theme to the opposite.
jsfunction ThemeButton() {
const { changeTheme } = useTheme()
return (
<button onClick={changeTheme}>Change Theme</button>
)
}
Copythight © All Rights Reserved.