themeflip
v0.2.0
Published
A lightweight React theme toggle for light, dark, and system themes.
Readme
themeflip
A lightweight React theme toggle for light, dark, and system themes.
Requirements
- React 18+
Install
npm install themeflipUsage
import { ThemeToggle } from "themeflip";
export default function App() {
return <ThemeToggle />;
}For Tailwind dark mode:
<ThemeToggle addDarkClass />Styling
themeflip is unstyled, so you can use Tailwind, vanilla CSS, CSS Modules, or any other styling system.
<ThemeToggle
className="theme-toggle"
buttonClassName="theme-toggle-button"
activeButtonClassName="active"
/>Data attributes
The component exposes data attributes so you can style it without depending on a specific CSS framework.
[data-theme-toggle] {
display: flex;
}
[data-theme-option][data-active="true"] {
font-weight: bold;
}
[data-theme-indicator][data-theme="dark"] {
transform: translateX(200%);
}Available attributes include:
data-theme-toggle— root elementdata-theme-indicator— active-theme indicatordata-theme="system | light | dark"— current selected themedata-theme-option="system | light | dark"— individual theme buttondata-active="true | false"— whether a theme button is selected
Props
defaultTheme—"light","dark", or"system"storageKey— localStorage key, defaults to"theme"addDarkClass— adds/removes thedarkclass on<html>onThemeChange— called when the selected theme changessystem,light,dark— customize labels and iconsclassNameindicatorClassNamebuttonClassNameactiveButtonClassName
Framework notes
Avoiding theme flicker
To apply the correct theme before React loads, you can optionally add this script near the top of your <head>:
<script>
(function () {
try {
var t = localStorage.getItem("theme");
var d =
t === "dark" ||
(t !== "light" &&
window.matchMedia("(prefers-color-scheme: dark)").matches);
document.documentElement.classList.toggle("dark", d);
} catch (e) {}
})();
</script>This is useful when using addDarkClass and helps avoid a brief light-theme flash while the page loads.
If you use a custom storageKey, replace "theme" in the script with the same key.
Astro
When using Astro, render the toggle as a client-only React island:
<ThemeToggle client:only="react" />Breaking changes (v0.2.0)
- Changed the default theme from
"auto"to"system" - Renamed the
autoprop tosystemfor consistency
License
MIT
