Implement Dark mode and light mode with TailwindCSS.
- Copy & paste this code in public/index.html
<script>
const defaultTheme = "dark";
if (!localStorage.getItem("theme")) {
localStorage.setItem("theme", defaultTheme);
}
if (localStorage.getItem("theme") === "dark") {
document.documentElement.classList.add("dark");
} else {
document.documentElement.classList.remove("dark");
}
</script>
- Create a function anywhere in your react project with this codeπ
const toggleTheme = () => {
const theme = localStorage.getItem("theme");
if (theme === "dark") {
document.documentElement.classList.remove("dark");
localStorage.setItem("theme", "light");
} else {
document.documentElement.classList.add("dark");
localStorage.setItem("theme", "dark");
}
};
- Now you can use toggleTheme function.
NOTE: in this example default theme is dark if you don't like dark as default then you can set the light theme as default.
just change defaultTheme variable value dark to light.
Top comments (0)