@philiprehberger/react-theme-provider
v0.1.6
Published
Dark/light/system theme provider for React with localStorage persistence and system preference detection
Readme
@philiprehberger/react-theme-provider
Dark/light/system theme provider for React with localStorage persistence and system preference detection
Installation
npm install @philiprehberger/react-theme-providerUsage
ThemeProvider
Wrap your app with the provider:
import { ThemeProvider } from '@philiprehberger/react-theme-provider';
function App() {
return (
<ThemeProvider defaultTheme="system" storageKey="theme">
<YourApp />
</ThemeProvider>
);
}useTheme
Access theme state from any component:
import { useTheme } from '@philiprehberger/react-theme-provider';
function MyComponent() {
const { theme, setTheme, resolvedTheme } = useTheme();
// theme: 'light' | 'dark' | 'system'
// resolvedTheme: 'light' | 'dark' (actual applied theme)
}ThemeToggle
Pre-built toggle component with sun/moon/system icons:
import { ThemeToggle } from '@philiprehberger/react-theme-provider';
<ThemeToggle />API
| Export | Type | Description |
|--------|------|-------------|
| ThemeProvider | Component | Context provider with localStorage persistence and system preference detection |
| useTheme() | Hook | Returns { theme, setTheme, resolvedTheme } for reading/setting theme |
| ThemeToggle | Component | Pre-built three-way toggle (light/dark/system) with sun/moon/system icons |
| Theme | Type | 'light' \| 'dark' \| 'system' |
| ResolvedTheme | Type | 'light' \| 'dark' (the actual applied theme) |
| ThemeContextType | Type | Shape of the theme context value |
| ThemeProviderProps | Type | Props for ThemeProvider (children, storageKey?, defaultTheme?) |
| ThemeToggleProps | Type | Props for ThemeToggle (className?, activeClassName?, inactiveClassName?) |
How It Works
- Applies
lightordarkclass todocument.documentElement - Persists user preference to
localStorage - Listens for system
prefers-color-schemechanges when set tosystem - Works with Tailwind CSS
dark:variant out of the box
Development
npm install
npm run build
npm testLicense
MIT
