コンテンツにスキップ

Next.js でダークモードに対応する

GitHub - pacocoursey/next-themes: Perfect Next.js dark mode in 2 lines of code. Support System preference and any other theme with no flashing

1
$ npm i next-themes
src/app/layout.tsx
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
export default async function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html suppressHydrationWarning>
      <body>
        <ThemeProvider>{children}</ThemeProvider>
      </body>
    </html>
  );
}
src/app/globals.css
1
2
3
4
5
6
7
8
9
:root {
  --color-background: #fff;
  --color-foreground: #000;
}

[data-theme="dark"] {
  --color-background: #000;
  --color-foreground: #fff;
}
src/app/LightSwitch.tsx
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
"use client";

import { useTheme } from "next-themes";
import { useEffect, useState } from "react";

export function LightSwitch() {
  const [mounted, setMounted] = useState(false);
  const { theme, setTheme } = useTheme();

  useEffect(() => {
    setMounted(true);
  }, []);

  if (!mounted) {
    return null;
  }

  return (
    <div>
      The current theme is: {theme}
      <button onClick={() => setTheme("light")}>Light Mode</button>
      <button onClick={() => setTheme("dark")}>Dark Mode</button>
    </div>
  );
}