react-light-dark-mode
Version:
A react Library to build light and dark mode UI
97 lines (70 loc) • 2.44 kB
Markdown
# 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.
```JSX
import { DarkLightModeProvider } from "react-light-dark-mode";
ReactDOM.render(
<DarkLightModeProvider>
<App />
</DarkLightModeProvider>,
document.getElementById("root")
);
```
2. 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).
```JSX
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;
```
3. 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.
```HTML
<body class="_darkMode_"></body>
```
Else if `lightMode = true` then.
```HTML
<body class="_lightMode_"></body>
```
```CSS
._darkMode_ .buttonColor {
background-color: "white";
}
._lightMode_ .buttonColor {
background-color: "black";
}
```
4. If CSS classes won't get the job done for you, then you can also use the `lightMode` property to conditionally
render content
5. 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.