Color Mode
Adding support for light and dark color mode
Saas UI uses next-themes
to add support for light and dark color mode.
Composition
import {
ColorModeTrigger,
DarkMode,
LightMode,
useColorMode,
useColorModeValue,
} from '@saas-ui/react/color-mode'
useColorMode
The useColorMode
hook returns the current color mode and a function to toggle
the color mode.
'use client'
import { Button, useColorMode } from '@saas-ui/react'
export const ColorModeBasic = () => {
const { toggleColorMode } = useColorMode()
return (
<Button variant="outline" onClick={toggleColorMode}>
Toggle Mode
</Button>
)
}
Calling toggleColorMode
or setColorMode
anywhere in your app tree toggles
the color mode from light or dark and vice versa.
useColorModeValue
The useColorModeValue
hook returns a value based on the current color mode.
Here's the signature:
const result = useColorModeValue('<light-mode-value>', '<dark-mode-value>')
The value returned will be the value of the light mode if the color mode is
light
, and the value of the dark mode if the color mode is dark
.
'use client'
import {
Box,
Button,
Stack,
useColorMode,
useColorModeValue,
} from '@saas-ui/react'
export const ColorModeValue = () => {
const { toggleColorMode } = useColorMode()
const bg = useColorModeValue('red.500', 'red.200')
const color = useColorModeValue('white', 'gray.800')
return (
<Stack align="flex-start" gap="4">
<Box p="2" bg={bg} color={color}>
This box's style will change based on the color mode.
</Box>
<Button variant="outline" size="sm" onClick={toggleColorMode}>
Toggle Mode
</Button>
</Stack>
)
}
Hydration Mismatch
When using useColorModeValue
or useColorMode
in SSR, you may notice a
hydration mismatch when the page is mounted. This is because the color mode
value is computed on the server side.
To avoid this, use the ClientOnly
component to wrap the component that uses
useColorModeValue
and render a skeleton until mounted on the client side.
'use client'
import { ClientOnly, IconButton, Skeleton, useColorMode } from '@saas-ui/react'
import { LuMoon, LuSun } from 'react-icons/lu'
export const ColorModeValueFallback = () => {
const { toggleColorMode, colorMode } = useColorMode()
return (
<ClientOnly fallback={<Skeleton boxSize="8" />}>
<IconButton onClick={toggleColorMode} variant="outline" size="sm">
{colorMode === 'light' ? <LuSun /> : <LuMoon />}
</IconButton>
</ClientOnly>
)
}
Forced Color Mode
Using the LightMode
and DarkMode
components it's possible to force the color
mode for a specific component or a group of components.
'use client'
import {
Button,
DarkMode,
HStack,
LightMode,
useColorMode,
} from '@saas-ui/react'
export const ColorModeForced = () => {
const { toggleColorMode } = useColorMode()
return (
<HStack>
<LightMode>
<Button size="sm" variant="subtle">
Light Mode Always
</Button>
</LightMode>
<DarkMode>
<Button size="sm" variant="subtle">
Dark Mode Always
</Button>
</DarkMode>
<Button size="sm" variant="subtle" onClick={toggleColorMode}>
Toggle Mode
</Button>
</HStack>
)
}