Theme provider
Set and save the theme, accent, font, corners, density and direction from React with useTheme(), and avoid the first-paint flash with themeScript().
Source@monoline/react 0.4.0Markdown for AI toolsstable
- Built on native elements
- 5 parts, named exports
- The theme follows the system colour scheme until the user chooses one.
- ThemeSwitcher is a labelled group of native selects, fully keyboard operable.
- Changing direction also sets dir on the page so arrow keys follow the reading direction.
Import
import '@monoline/css';
import {ThemeProvider} from '@monoline/react';
Not installed yet? Pick a route.
Copies the source and its styles into your project.
npx monoline add theme-provider
Usage
import {Button, ThemeProvider, ThemeSwitcher, useTheme} from '@monoline/react';
function Controls() {
const {theme, resolvedTheme, accent, density, setTheme, setDensity} = useTheme();
return (
<div style={{display: 'grid', gap: 12}}>
<ThemeSwitcher />
<p>Theme: {theme}{theme === 'system' ? ` (${resolvedTheme})` : ''}. Accent: {accent}. Density: {density}.</p>
<div style={{display: 'flex', gap: 8}}>
<Button variant="line" onClick={() => setTheme(resolvedTheme === 'dark' ? 'warm' : 'dark')}>Toggle dark</Button>
<Button variant="line" onClick={() => setDensity(density === 'compact' ? 'comfortable' : 'compact')}>Toggle compact</Button>
</div>
</div>
);
}
<ThemeProvider storageKey="monoline-demo">
<Controls />
</ThemeProvider>
Anatomy
Import the parts you need and nest them like this.
import {ThemeProvider, useTheme, themeScript, themeOptions, ThemeSwitcher} from '@monoline/react';
<ThemeProvider>
<useTheme />
<themeScript />
<themeOptions />
<ThemeSwitcher />
</ThemeProvider>
Examples
useTheme and ThemeSwitcher
ThemeProvider writes data-theme, data-accent and the other options to <html> and saves them. On a server-rendered page also put <script dangerouslySetInnerHTML={{__html: themeScript()}} /> in <head>.
Props
ThemeProviderProps
| Prop | Type | Default | Description |
|---|---|---|---|
storageKey | string | 'monoline' | Prefix of the localStorage keys, e.g. `monoline` stores `monoline-theme`. Default "monoline". Match it in `themeScript`. |
children | ReactNode | – | The app. |
theme | Theme | – | |
accent | Accent | – | |
font | Font | – | |
radius | Radius | – | |
density | Density | – | |
dir | Dir | – |
Accessibility
- The theme follows the system colour scheme until the user chooses one.
- ThemeSwitcher is a labelled group of native selects, fully keyboard operable.
- Changing direction also sets dir on the page so arrow keys follow the reading direction.