This library for Reactjs includes two hooks:
- useDocTheme
- Supports dark, light and system theme with body class of
dark. - Supports Tailwind CSS.
- By default apply system theme.
- Supports dark, light and system theme with body class of
- useLocalStorage
- Supports saving and loading data from browser's local storage.
npm install use-doc-theme --save
@latestversion supports React 18.3.1. Use@0.2.0for earlier React versions.
See the demo, built with Reactjs and pure CSS: https://codepen.io/gauravjot/full/yLQexGR
In your App.tsx or layout.tsx file, wrap your app with ThemeProvider.
import { ThemeProvider } from "use-doc-theme";
export default function App() {
return (
<ThemeProvider>
{...your other components}
</ThemeProvider>
);
}This will detect the user's selected theme or theme set by system.
Intializing the hook to access various theme controls.
/* import */
import { useDocTheme } from "use-doc-theme";
function App() {
/* initialize */
const theme = useDocTheme();
return (
<>
{/* usage */}
<button onClick={theme.toggle}>Toggle</button>
</>
);
}These are all the available methods and options.
const theme = useDocTheme();
// Apply Light
theme.light();
// Apply Dark
theme.dark();
// Apply System
theme.system();
// Toggle
theme.toggle();
// Check active theme
if (theme.isLightMode) {
// Light Theme is active
}
if (theme.isDarkMode) {
// Dark Theme is active
}
if (theme.isSystemMode) {
// System Theme is active
}Add this to your tailwind.config.js file.
module.exports = {
darkMode: 'class',
// ...
}Learn more here: Dark Mode - Tailwind CSS.
Use .dark class. For example:
.hello {
background: white;
color: black;
}
.dark .hello {
/* dark theme */
background: black;
color: white;
}For body tag, use
body.dark {
/* dark theme */
background: black;
color: white;
}It behaves identical to useState with a plus that the state is saved in local storage and therefore persist over sessions.
You need to provide a unique key and a default value if the value is not available in local storage.
import { useLocalStorage } from "use-doc-theme";
function App() {
const [book, setBook] = useLocalStorage<string>(
"book", /* key */
"The Alchemist by Paulo Coelho" /* default value */
);
return (
<>
<button
onClick={() => {
setBook("Happy Place by Emily Henry");
}}
>
Switch Book
</button>
<h1>Current book</h1>
<p>{book}</p>
</>
);
}Data saved into local storage gets JSON stringified so you may also save objects.
Community contributions are welcomed.
