UNPKG

rc-theme-switcher

Version:

A simple Theme/Style Manager for React that allows switching between **light**, **dark**, and **custom themes**, supports **system preference**. Perfect for React projects of any size. It uses React Context API + localStorage to persist theme across sess

135 lines (93 loc) 2.48 kB
# rc-theme-switcher A simple Theme/Style Manager for React that allows switching between **light**, **dark**, and **custom themes**, supports **system preference**. Perfect for React projects of any size. It uses React Context API + localStorage to persist theme across sessions. --- ## ✨ Features - 🌙 Supports light/dark mode out of the box - 🖌️ Custom themes supported - 💾 Saves theme in `localStorage` - 🎨 Automatically detects system color scheme - Simple hook API (`useTheme`) --- --- ## Installation Using npm: ```bash npm install rc-theme-switcher ``` Using yarn: ```bash yarn add rc-theme-switcher ``` Basic Usage ```jsx import React from "react"; import { ThemeProvider, useTheme } from "rc-theme-switcher"; import "rc-theme-switcher/dist/theme.css"; const ThemeSwitcherButton = () => { const { theme, toggleTheme } = useTheme(); return <button onClick={toggleTheme}>Switch Theme (Current: {theme})</button>; }; function App() { return ( <ThemeProvider defaultTheme="light"> <div> <h1>Hello Theme Switcher!</h1> <ThemeSwitcherButton /> </div> </ThemeProvider> ); } export default App; ``` 🎯 API ```jsx ThemeProvider Props: defaultTheme (optional): "light" | "dark" | string (default: "light") useTheme() Returns: theme: current theme name toggleTheme(): switch between light/dark setCustomTheme(name: string): set a custom theme ``` 🛠️ How it works ```bash On first load: Checks localStorage for saved theme If none found, matches system preference (prefers-color-scheme) Updates <body data-theme="..."> for CSS usage ``` Advanced Usage System Preference Auto Detection ```jsx <ThemeProvider defaultTheme="light" useSystemPreference> <YourAppComponents /> </ThemeProvider> ``` useSystemPreference prop enables automatic detection of the user's system theme (prefers-color-scheme). Custom Themes ```jsx <ThemeProvider defaultTheme="light"> <button onClick={() => setCustomTheme("blue")}>Blue Theme</button> </ThemeProvider> ``` Define CSS for your custom theme: ```css :root[data-theme="light"] { --bg: #ffffff; --text: #000000; } :root[data-theme="dark"] { --bg: #1a1a1a; --text: #ffffff; } :root[data-theme="blue"] { --bg: #001f3f; --text: #ffffff; } body { background: var(--bg); color: var(--text); } ```