1.0.7 • Published 2 years ago

react-light-dark-mode v1.0.7

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

REACT LIGHT/DARK MODE

A library for switching between dark/light theme. This library uses REACT context API under the hood.

Technologies Used

  • HTML
  • JavaScript
  • React

Features

  • Dark/light mode switch function.
  • A custom lightMode variable.
  • Persisting on page refresh.

Installation

npm install react-light-dark-mode

How to use

  1. Firstly lets wrap our <App/> component in <DarkLightModeProvider/> as shown below. So that the whole app has access to the library.
import { DarkLightModeProvider } from "react-light-dark-mode";

ReactDOM.render(
<DarkLightModeProvider>
<App />
</DarkLightModeProvider>,

document.getElementById("root")
);
  1. Next we would need to import the DarkLightModeContext into our component. This library uses react context API, so we would need to import useContext as well. The DarkLightModeContext has two properties, i.e lightMode and toggleLightDarkMode. The toggleLightDarkMode method is used to alternate between light and dark mode, while the lightMode property stores the current theme. The default is lightMode = false (This implies dark mode is active and vice versa).
import React, { useContext } from "react";
import { DarkLightModeContext } from "react-light-dark-mode";

function App() {
  const { lightMode, toggleLightDarkMode } = useContext(DarkLightModeContext);

  const toggleMode = () => {
    toggleLightDarkMode();
  };

  return (
    <div>
      <button onClick={toggleMode} className="buttonColor">
         {lightMode ? "Light Mode Active" : "Dark Mode Active"}
      </button>
    </div>
  );
}

export default App;
  1. The library also adds an active class to the body of the html document. These classes can be used to style components for dark and light theme

If lightMode = false then.

<body class="_darkMode_"></body>

Else if lightMode = true then.

<body class="_lightMode_"></body>
._darkMode_ .buttonColor {
   background-color: "white";
}
._lightMode_ .buttonColor {
   background-color: "black";
}
  1. If CSS classes won't get the job done for you, then you can also use the lightMode property to conditionally render content

  2. This library also adds a localStorage item i.e lightMode which can again either be true or false. So it remembers the user's choice, even if the browser is closed or session ends.

1.0.7

2 years ago

1.0.6

2 years ago

1.0.5

2 years ago

1.0.4

2 years ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago