tailwind-theme-provider
v1.0.1
Published
A simple Tailwind CSS theme provider for React
Readme
Tailwind Theme Provider
A simple, reusable React component and hook for managing Tailwind CSS themes (dark, light, system).
Installation
npm install tailwind-theme-provider
# or
bun add tailwind-theme-provider
# or
yarn add tailwind-theme-providerUsage
Wrap your application with the ThemeProvider to provide the theme context to all children.
// App.tsx
import { ThemeProvider } from 'tailwind-theme-provider';
function App({ children }) {
return (
<ThemeProvider defaultTheme="system" storageKey="app-theme">
{children}
</ThemeProvider>
);
}Then, use the useTheme hook anywhere inside your app to read or change the current theme.
// ThemeSwitcher.tsx
import { useTheme } from 'tailwind-theme-provider';
export function ThemeSwitcher() {
const { theme, setTheme } = useTheme();
return (
<div>
<p>Current theme: {theme}</p>
<button onClick={() => setTheme('light')}>Light Mode</button>
<button onClick={() => setTheme('dark')}>Dark Mode</button>
<button onClick={() => setTheme('system')}>System Settings</button>
</div>
);
}Examples
// App.tsx
import { ThemeProvider } from 'tailwind-theme-provider';
function App({ children }) {
return (
<ThemeProvider defaultTheme="system" storageKey="app-theme" themes={['light', 'dark', 'rose', 'ocean', 'system']})>
{children}
</ThemeProvider>
);
}To work dakr mode and you custom theme you need to add this line in your index.css
@custom-variant dark (&:where(.dark, .dark *));
For here accoding the example the css file should look like
// index.css
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));
@custom-variant rose (&:where(.rose, .rose *));
@custom-variant ocean (&:where(.ocean, .ocean *));Features
- Persists Theme: Saves the theme to
localStorageautomatically. - System Sync: Syncs with system preferences when
systemtheme is selected. - Custom Themes: Pass an array of theme names to the
themesprop to support arbitrary custom themes (e.g.themes={['light', 'dark', 'rose', 'ocean', 'system']}). - Next.js App Router Compatible: Works seamlessly as a Client Component with the
"use client"directive. - Keyboard Shortcut: Press
D(when not focused on inputs) to quickly cycle through all available themes.
