Simplify theme toggle to dark/light only

- Remove system theme option
- Refactor ModeToggle component for immediate theme switching
- Implement local state management for smoother transitions
- Persist theme preference in localStorage
- Update icon display logic for better visual feedback

This commit addresses the issue of delayed theme switching and
simplifies the user experience by offering only dark and light modes.
This commit is contained in:
Abhiman panwar
2024-09-12 23:33:17 +05:30
parent 207969a919
commit 33619bcf69
2 changed files with 30 additions and 39 deletions

View File

@@ -51,6 +51,7 @@
"styled-components": "^6.1.12", "styled-components": "^6.1.12",
"tailwind-merge": "^2.5.1", "tailwind-merge": "^2.5.1",
"tailwindcss-animate": "^1.0.7", "tailwindcss-animate": "^1.0.7",
"zen-website": "file:",
"zod": "^3.23.8" "zod": "^3.23.8"
}, },
"devDependencies": { "devDependencies": {

View File

@@ -1,50 +1,40 @@
"use client"; "use client";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { MoonIcon, SunIcon } from "@radix-ui/react-icons"; import { MoonIcon, SunIcon } from "@radix-ui/react-icons";
import { useTheme } from "next-themes"; import { useTheme } from "next-themes";
import { Button } from "./ui/button"; import { Button } from "./ui/button";
export function ModeToggle() { export function ModeToggle() {
const { theme, setTheme } = useTheme(); const { setTheme } = useTheme();
const [currentTheme, setCurrentTheme] = useState('light');
const [mounted, setMounted] = useState(false);
const toggleTheme = () => { useEffect(() => {
switch (theme) { setMounted(true);
case "system": const savedTheme = localStorage.getItem('theme') || 'light';
setTheme("dark"); setCurrentTheme(savedTheme);
break; setTheme(savedTheme);
case "dark": }, [setTheme]);
setTheme("light");
break;
case "light":
setTheme("system");
break;
}
};
// prevent hydration error const toggleTheme = () => {
const [mounted, setMounted] = useState(false); const newTheme = currentTheme === 'light' ? 'dark' : 'light';
setCurrentTheme(newTheme);
setTheme(newTheme);
localStorage.setItem('theme', newTheme);
};
useEffect(() => { if (!mounted) {
setMounted(true); return null;
}, []); }
if (!mounted) { return (
return null; <Button variant="ghost" size="icon" onClick={toggleTheme}>
} {currentTheme === 'light' ? (
<SunIcon className="h-[1.2rem] w-[1.2rem]" />
return ( ) : (
<Button variant="ghost" size="icon" onClick={toggleTheme}> <MoonIcon className="h-[1.2rem] w-[1.2rem]" />
<MoonIcon )}
className={`${theme === "system" ? "visible" : "hidden"} h-[1.2rem] w-[1.2rem]`} <span className="sr-only">Toggle theme</span>
/> </Button>
<SunIcon );
className={`${theme === "light" ? "visible" : "hidden"} h-[1.2rem] w-[1.2rem]`}
/>
<MoonIcon
className={`${theme === "dark" ? "visible" : "hidden"} h-[1.2rem] w-[1.2rem]`}
/>
<span className="sr-only">Toggle theme</span>
</Button>
);
} }