Color Modes
Color modes can be used to create a user-configurable dark mode or any number of other color modes.
Defining colors
In the theme.colors
object, add a nested modes
object that will contain keys for the non-default color palette mode.
Add an initialColorMode
value to the theme to initialize the default state.
// example theme colors
{
initialColorMode: 'light',
colors: {
text: '#000',
background: '#fff',
primary: '#07c',
modes: {
dark: {
text: '#fff',
background: '#000',
primary: '#0cf',
}
}
}
}
Setting the color mode
Use the useColorMode
hook in your application to change the color mode.
This value will be stored in localStorage
and used whenever the page is loaded.
import React from 'react'
import { useColorMode } from 'theme-ui'
export default props => {
const [ colorMode, setColorMode ] = useColorMode()
return (
<header>
<button
onClick={e => {
setColorMode(colorMode === 'light' ? 'dark' : 'light')
}}>
Toggle
{' '}
{colorMode === 'light' ? 'Dark' : 'Light'}
</button>
</header>
)
}
Applying colors
The previous steps will enable a color mode state and pass it through context.
To apply the color mode values to the <body>
element, render the ColorMode
component in your application.
import React from 'react'
import { ThemeProvider, ColorMode } from 'theme-ui'
import theme from './theme'
export default props =>
<ThemeProvider theme={theme}>
<ColorMode />
{props.children}
</ThemeProvider>
Gatsby plugin
For use with Gatsby, use the gatsby-plugin-theme-ui
to add the ThemeProvider to the root of your application.
The plugin will also attempt to prevent the flash of colors that can happen during page load when a user has a non-default color mode set.
This plugin will look for a src/theme.js
file to import and pass to the ThemeProvider.
// gatsby-config.js
module.exports = {
plugins: [
'gatsby-plugin-theme-ui',
],
}
See the Gatsby plugin docs for more info.
(prefers-color-scheme: dark)
media query
This feature will detect the (prefers-color-scheme: dark)
media query to initialize the state as dark
.
Currently it does not check for (prefers-color-scheme: light)
.