Switching Themes
Yamada UI provides the functionality for users to switch themes.
Setup
- 1
Generate a Theme
Use the CLI to generate a theme.
Before running the following commands, you need to install@yamada-ui/cliand execute theinitcommand. For more details, please see here.pnpm yamada-cli themenpm yamada-cli themeyarn yamada-cli themebun yamada-cli theme - 2
Add a Theme
Change the
index.tsin the generated theme.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
Update the Provider
Set the generated theme to
UIProvider.import { UIProvider } from "@workspaces/ui" import { theme } from "@workspace/theme" const App = () => { return ( <UIProvider theme={theme}> <YourApplication /> </UIProvider> ) } - 4
Add a Logic
Use
useThemeto switch themes.useThemereturns thethemeSchemeandchangeThemeSchemeto change the theme scheme.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> )If you use this code, you need to add"use client"to the top of the file.
Change the Default Theme Scheme
To change the default theme scheme, set the value to config.ts in defaultThemeScheme.
- 1
Change the Config
Change the
config.tsin the generated theme.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
Update the Provider
Set the generated theme to
UIProvider.import { UIProvider } from "@workspaces/ui" import { theme, config } from "@workspace/theme" const App = () => { return ( <UIProvider theme={theme} config={config}> <YourApplication /> </UIProvider> ) }