Add dark mode with next-themes

This commit is contained in:
Defectink
2022-03-22 11:55:03 +08:00
parent 97f2275ce7
commit bc7ada8abc
8 changed files with 75 additions and 18 deletions

View File

@ -0,0 +1,30 @@
import { useTheme } from 'next-themes';
import { FC, useEffect, useState } from 'react';
import { FiMoon, FiSun } from 'react-icons/fi';
const DarkModeBtn: FC = () => {
const [mounted, setMounted] = useState(false);
const { systemTheme, theme, setTheme } = useTheme();
// When mounted on client, now we can show the UI
useEffect(() => setMounted(true), []);
const currentTheme = theme === 'system' ? systemTheme : theme;
if (!mounted) return null;
return (
<>
{currentTheme === 'dark' ? (
<button>
<FiSun className="w-5 h-5" onClick={() => setTheme('light')} />
</button>
) : (
<button>
<FiMoon className="w-5 h-5" onClick={() => setTheme('dark')} />
</button>
)}
</>
);
};
export default DarkModeBtn;

View File

@ -2,6 +2,9 @@ import cn from 'classnames';
import Link from 'next/link';
import { FC, useState } from 'react';
import { FiMenu } from 'react-icons/fi';
import dynamic from 'next/dynamic';
const DarkModeBtn = dynamic(() => import('components/DarkModeBtn'));
const txtMenu = [
{
@ -68,6 +71,15 @@ const HeadBar: FC = () => {
<Link href={m.path}>{m.name}</Link>
</li>
))}
<li
className={cn(
'mb-2 last:mb-0 md:mb-0',
'md:mr-4 md:last:mr-0',
'flex items-center'
)}
>
<DarkModeBtn />
</li>
</ul>
</nav>
</header>