use-dark-hook

0.2.2 • Public • Published

use-dark-hook

A light-weight and straight forward library that adds 'dark mode' in your web app using React Hook.

npm version

use-dark-hook uses LocalStorage to store the current mode (DARK/LIGHT) and the selected mode will be loaded even if you close your app and open again. Also, if you open your app for the first time, it detects the User System Theme, i.e. what color scheme they have on their system (dark mode / light mode), and changes the current mode automatically. (The browser must support prefers-color-scheme in order that to work).

Preview

use-dark-hook example

Compatibility

Your React App needs to be 16.8.0 or later to use React Hooks.

Installation

$ npm i use-dark-hook

Usage

Import use-dark-hook in your React App 📦 and use the hook like this:

import { useDarkHook } from 'use-dark-hook';
 
const App = () => {
  const [mode, toggleMode] = useDarkHook();
 
  return (
    <div className="App">
      <h2>Current Mode: {mode}</h2>
      <button onClick={() => toggleMode()} className={`${mode}_cta`}>
        ☀ / ☾
      </button>
    </div>
  );
};

And, you need to add below CSS classes to your stylesheet. Of course, feel free to change the colors as per your taste 🤪

:root {
  --main-bg-light: #fefefe;
  --main-bg-dark: #232323;
  --text-light: #ffffff;
  --text-dark: #333333;
}
 
.dark {
  background-color: var(--main-bg-dark);
  color: var(--text-light);
}
 
.light {
  background-color: var(--main-bg-light);
  color: var(--text-dark);
}
 
@media (prefers-color-scheme: dark) {
  body {
    background-color: var(--main-bg-dark);
    color: var(--text-light);
    transition: background-color 0.2s ease;
  }
}
 
@media (prefers-color-scheme: light) {
  body {
    background-color: var(--main-bg-light);
    color: var(--text-dark);
    transition: background-color 0.2s ease;
  }
}

Enjoy Dark Mode 🎉🎉🎉

❤️ it? Give a ⭐️ on GitHub


Default Mode

You can also set the default mode, when your React App loads for the first time. You can pass dark OR light while setting your hooks.

Example

const [mode, toggleMode] = useDarkHook('dark');

Please feel free to raise a PR if you have anything to correct me or add any features, you can also reach me over email 🤑

License

MIT Licensed

Package Sidebar

Install

npm i use-dark-hook

Weekly Downloads

1

Version

0.2.2

License

MIT

Unpacked Size

135 kB

Total Files

14

Last publish

Collaborators

  • iamdebadipti