ファランクス by ponta

Shadcn-ui : dark mode

dark modeの導入

npm install next-themes
  • 必要なコンポーネント:
npx shadcn-ui@latest add button
npx shadcn-ui@latest add dropdown-menu
  • 必要なファイル:theme-provider.jsx
"use client";

import * as React from "react";
import { ThemeProvider as NextThemesProvider } from "next-themes";

export function ThemeProvider({ children, ...props }) {
  return <NextThemesProvider {...props}>{children}</NextThemesProvider>;
}
  • layout.jsxでmain要素をThemeProviderで囲う
<ThemeProvider
          attribute="class"
          defaultTheme="dark"
          enableSystem
          disableTransitionOnChange
        >
  • defaultTheme="system” の部分が “dark” だとデフォルトがダークテーマになる

defaultTheme=systemでなく、lightでおk

export interface UseThemeProps {
    /** List of all available theme names */
    themes: string[];
    /** Forced theme name for the current page */
    forcedTheme?: string;
    /** Update the theme */
    setTheme: (theme: string) => void;
    /** Active theme name */
    theme?: string;
    /** If `enableSystem` is true and the active theme is "system", this returns whether the system preference resolved to "dark" or "light". Otherwise, identical to `theme` */
    resolvedTheme?: string;
    /** If enableSystem is true, returns the System theme preference ("dark" or "light"), regardless what the active theme is */
    systemTheme?: 'dark' | 'light';
}
  • providerをたどっていったファイル内で ↑ systemTheme?: 'dark' | 'light'; とあるので、layout.tsxの<ThemeProvider >内は defaultTheme="light" で良いはず

light / darkの内容を変えたい場合

①公式のテーマを利用する

https://ui.shadcn.com/themes

テーマコードをコピー

globals.cssを変えたいテーマのコードで上書きする


②自分で内容を変える

HSL(色相、彩度、明度)= 色空間の値

bacground は背景、Cardはカードコンポーネントなど、それぞれ設定できる

  • background . card . popover の内容を共通にするとそれらの間に差異が発生しない。

あえて違いを設けるのもあり。

例:Cardだけ背景が違うと立体的になる

← Go home