テーマの切り替え
Yamada UIは、ユーザーがテーマを切り替える機能を提供しています。
セットアップ
- 1
- 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"
PrimarySecondaryPrimarySecondaryconst { themeScheme, changeThemeScheme } = useTheme() return ( <VStack> <Text>The current scheme is "{themeScheme}"</Text> <Wrap gap="md" alignItems="center"> <Badge colorScheme="primary">Primary</Badge> <Badge colorScheme="secondary">Secondary</Badge> <Tag colorScheme="primary">Primary</Tag> <Tag colorScheme="secondary">Secondary</Tag> </Wrap> <Wrap gap="md"> <Button onClick={() => changeThemeScheme("base")}>Base Theme</Button> <Button colorScheme="red" onClick={() => changeThemeScheme("red")}> Red Theme </Button> <Button colorScheme="green" onClick={() => changeThemeScheme("green")}> Green Theme </Button> <Button colorScheme="blue" onClick={() => changeThemeScheme("blue")}> Blue Theme </Button> </Wrap> </VStack> )こちらのコードを使用する場合は、"use client"をファイルの上部に追加する必要があります。
デフォルトのテーマスキームを変更する
デフォルトのテーマスキームを変更する場合は、config.tsのdefaultThemeSchemeに値を設定します。
- 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> ) }