テーマの切り替え

Yamada UIは、ユーザーがテーマを切り替える機能を提供しています。

セットアップ

  • 1

    テーマを生成する

    CLIを使用してテーマを生成します。

    pnpm yamada-cli theme
    
  • 2

    テーマを追加する

    生成したテーマのindex.tsを変更します。

    theme/index.ts

    import { defineTheme } from "@yamada-ui/react"
    import { semanticTokens } from "./semantic-tokens"
    import { styles } from "./styles"
    import { tokens } from "./tokens"
    
    export { config } from "./config"
    
    export const theme = defineTheme({
      styles,
      ...tokens,
      semanticTokens,
      themeSchemes: {
        blue: { semanticTokens: { colorSchemes: { primary: "blue" } } },
        red: { semanticTokens: { colorSchemes: { primary: "red" } } },
        green: { semanticTokens: { colorSchemes: { primary: "green" } } },
      },
    })
    
    export type Theme = typeof theme
    
  • 3

    プロバイダーを更新する

    生成したテーマをUIProviderに設定します。

    import { UIProvider } from "@workspaces/ui"
    import { theme } from "@workspace/theme"
    
    const App = () => {
      return (
        <UIProvider theme={theme}>
          <YourApplication />
        </UIProvider>
      )
    }
    
  • 4

    ロジックを追加する

    useThemeを使用してテーマを切り替えます。useThemeは、現在のテーマスキームのthemeSchemeとテーマスキームを変更するchangeThemeSchemeを返します。

    The current scheme is "base"

    PrimarySecondaryPrimarySecondary

デフォルトのテーマスキームを変更する

デフォルトのテーマスキームを変更する場合は、config.tsdefaultThemeSchemeに値を設定します。

  • 1

    コンフィグを変更する

    生成したテーマのconfig.tsを変更します。

    theme/config.ts

    import { defineConfig } from "@yamada-ui/react"
    
    export const config = defineConfig({
      css: { varPrefix: "ui" },
      breakpoint: { direction: "down", identifier: "@media screen" },
      defaultColorMode: "dark",
      defaultThemeScheme: "blue", 
      notice: { duration: 5000 },
      theme: { responsive: true },
    })
    
  • 2

    プロバイダーを更新する

    生成したテーマをUIProviderに設定します。

    import { UIProvider } from "@workspaces/ui"
    import { theme, config } from "@workspace/theme"
    
    const App = () => {
      return (
        <UIProvider theme={theme} config={config}>
          <YourApplication />
        </UIProvider>
      )
    }