@deepeka2412/react-theme-switcher
v1.0.0
Published
A simple and lightweight React theme switcher with system preference support
Downloads
6
Maintainers
Readme
react-theme-switcher
A simple and lightweight React theme switcher with system preference support.
Features
- 🌙 Dark/Light theme switching
- 💻 System preference detection
- 💾 Persistent theme storage
- ⚡ Lightweight and performant
- 🎯 TypeScript support
- 🔧 Easy to integrate
Installation
npm install react-theme-switcherQuick Start
import { ThemeProvider, useTheme } from "react-theme-switcher";
function App() {
return (
<ThemeProvider>
<Main />
</ThemeProvider>
);
}
function Main() {
const { theme, setTheme, toggleTheme } = useTheme();
return (
<div>
<p>Current theme: {theme}</p>
<button onClick={toggleTheme}>Toggle</button>
<button onClick={() => setTheme("dark")}>Dark</button>
<button onClick={() => setTheme("light")}>Light</button>
<button onClick={() => setTheme("system")}>System</button>
</div>
);
}API
ThemeProvider
The main provider component that wraps your app.
<ThemeProvider>
<YourApp />
</ThemeProvider>useTheme
A hook that provides theme state and functions.
Returns
theme: "light" | "dark" | "system"- Current themesetTheme: (theme: "light" | "dark" | "system") => void- Function to set themetoggleTheme: () => void- Function to toggle between light and dark
CSS Integration
The package adds CSS classes to the html element:
html.light {
--bg: #ffffff;
--text: #000000;
}
html.dark {
--bg: #000000;
--text: #ffffff;
}Then use CSS variables in your components:
function Card() {
return (
<div style={{ background: "var(--bg)", color: "var(--text)" }}>
Themed Card
</div>
);
}System Preference
When theme is set to "system", it automatically follows the user's system preference:
(prefers-color-scheme: dark)→ Dark theme(prefers-color-scheme: light)→ Light theme
Persistence
Theme preferences are automatically saved to localStorage and restored on page reload.
License
MIT
