Dark Mode
Learn how to use dark mode in Chakra UI applications
Chakra relies on the next-themes
library to provide dark mode support. During
the installation process, the snippets required to get started are added to your
project via the CLI.
If you haven't already, you can add the next-themes
library to your project
via the CLI.
npx @chakra-ui/cli@next snippet add color-mode
The generated snippets consists of the following:
ColorModeProvider
: composes thenext-themes
provider componentuseColorMode
: provides the current color mode and a function to toggle the color modeuseColorModeValue
: returns the correct value based on the current color modeColorModeButton
: can be used to toggle the color mode
Wrap your app with the ColorModeProvider
and use the useColorMode
hook to
access and toggle the color mode.
import { ColorModeProvider } from "@/components/ui/color-mode"
import { ChakraProvider, defaultSystem } from "@chakra-ui/react"
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<ChakraProvider theme={defaultSystem}>
<ColorModeProvider>{children}</ColorModeProvider>
</ChakraProvider>
)
}
Use the ColorModeButton
component to toggle the color mode.
import { ColorModeButton } from "@/components/ui/color-mode"
export default function Page({ children }: { children: React.ReactNode }) {
return (
<>
<ColorModeButton />
{children}
</>
)
}
Use the _dark
condition to style components for dark mode.
<Box bg={{ base: "white", _dark: "black" }}>
<Text>Hello</Text>
</Box>
or
<Box bg="white" _dark={{ bg: "black" }}>
<Text>Hello</Text>
</Box>
To reduce the amount of code you need to write, use semantic tokens to style components for dark mode. This ensures the light and dark mode styles are applied automatically and consistently.
Chakra provides a set of semantic tokens that you can use to style components for dark mode. Learn more about
.<Box bg="bg.subtle">
<Text>Hello</Text>
</Box>
To force dark mode, set the dark
className on any parent element, or the root
element of your application.
<Box bg="black" className="dark">
<Box bg="bg.subtle">
<Text>Hello</Text>
</Box>
</Box>
Use the ColorModeProvider
component to set the dark mode for a page.
<ColorModeProvider forcedTheme="dark">
<Box bg="black" className="dark">
<Box bg="bg.subtle">
<Text>Hello</Text>
</Box>
</Box>
</ColorModeProvider>
Follow this next-themes
guide to learn more about