react-light-dark-mode
v1.0.7
Published
A react Library to build light and dark mode UI
Downloads
24
Maintainers
Readme
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
- 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")
);
- 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;
- 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";
}
If CSS classes won't get the job done for you, then you can also use the
lightMode
property to conditionally render contentThis library also adds a
localStorage item
i.elightMode
which can again either be true or false. So it remembers the user's choice, even if the browser is closed or session ends.