1.1.0 • Published 4 years ago

dark-mode-react-hook v1.1.0

Weekly downloads
6
License
ISC
Repository
github
Last release
4 years ago

React Hook Dark Mode

This package contains a React custom hook that applies dark mode to your website. It uses css filter to transform light schemes into dark themes (and viceversa). I took the idea from this post and extracted it into a single hook.

It works by injecting a global stylesheet with the following css:

html {
  filter: invert(1) hue-rotate(180deg);
}

img {
  
  filter: invert(1) hue-rotate(180deg);
}

.no-dark-mode {
  filter: invert(1) hue-rotate(180deg);
}

What this css is doing is inverting the colors in the <body> and then converting all colors to their complementaries. The final result is a dark variant (or light, if the original is dark) of the theme, while more-or-less keeping the main colors.

If there is an element that you do not wish to invert (for example, a dark modal background should probably not be bright under dark-mode), you can apply the no-dark-mode class to it.

Installation

npm i --save react-hook-dark-mode
# or
yarn add react-hook-dark-mode

Usage

import useDarkMode from "react-hook-dark-mode";

function darkModeToggle() {
  const [darkMode, setDarkMode] = useDarkMode();

  return (
    <button onClick={() => setDarkMode(!darkMode)}>
      {darkMode ? 🌙 : ☀️}
    </button>
  )
}

Options

The hook accepts a configuration object with the following options:

NameTypeDescriptionDefault
autoDetectbooleanUse a prefers-color-scheme media query to detect user preferences and automatically set dark modetrue
defaultValuebooleanApply dark mode by defaultfalse