use-theme-switcher
Because Dark Mode is not enough!
A React hook to switch between multiple themes, including dark mode and more! And the best part? No "white flash of death"!
Demo
Gatsby Plugin 👀
Using Gatsby?, checkout this plugin instead:
https://github.com/infoxicator/gatsby-plugin-theme-switcher
Install
yarn add use-theme-switcher
or
npm i -S use-theme-switcher
Usage with NextJS
ThemeScriptTag
to _document
.
Add the This script prevents the white flash of death
for static rendered sites. It is very important that the script is added just after the opening body tag and before any other content.
You can also pass the name of your default light and dark themes as props. These defaults will be used when visitor come to your site for the first time and will try to match their preference using window.matchMedia("(prefers-color-scheme: dark)");
and the default light theme if this cannot be determined.
; { return <Html lang="en"> <Head> </Head> <body> <ThemeScriptTag defaultDarkTheme="theme-dark" defaultLightTheme="theme-light" /> <Main /> <NextScript /> </body> </Html> }
ThemeProvider
to _app.js
Add the ; { return <ThemeProvider> <Component ...pageProps /> </ThemeProvider>}
Add your themes
This plugin adds a custom class name to the body
element of your site and uses CSS variables to customise your color scheme. Add your themes with the .theme-*
format:
Switching Themes
To switch themes, use the ThemeContext
hook.
; const theme switchTheme = ;
Add A Theme Switcher Component
You can implement your own theme switcher component but here is a basic example:
; const myThemes = id: "theme-midnightgreen" name: "Midnight Green" id: "theme-spacegray" name: "Space Gray" id: "theme-twitter" name: "Twitter Dark" const ThemePicker = { if theme return <div> myThemes </div> ; return null;}; ;
ThemeScriptTag
Properties
Prop | Description |
---|---|
defaultDarkTheme |
Initial theme name when prefers-color-scheme: dark |
defaultLightTheme |
Initial theme name when preference cannot be determined |
themeStorageKey |
Key to persist the theme name in localStorage . Default = "theme" . |
minify |
Minify the injected script using Terser. Default = true . |
themeStorageKey
Custom If you want to change the themeStorageKey
, ensure the same prop value is passed to both the ThemeScriptTag
and the ThemeProvider
. Example:
{ return <ThemeProvider themeStorageKey='my-custom-key'> <Component ...pageProps /> </ThemeProvider>}
{ return <Html lang="en"> <Head> </Head> <body> <ThemeScriptTag defaultDarkTheme="theme-dark" defaultLightTheme="theme-light" themeStorageKey='my-custom-key' /> <Main /> <NextScript /> </body> </Html> }
Credit
This plugin is based on the work and inspired by Sam Larsen-Disney and Josh Comeau
LICENSE
MIT LICENSE