// Dark Mode in React using Local Storage
import React from "react";
import { useState, useEffect } from "react";
const Home = () => {
const [mode, setMode] = useState("light");
const storedMode = localStorage.getItem("mode");
if (storedMode == null) {
localStorage.setItem("mode", "light");
}
useEffect(() => {
setMode(storedMode);
}, []);
const handleClick = () => {
if (storedMode == "light" || storedMode === null) {
localStorage.removeItem("mode");
localStorage.setItem("mode", "dark");
setMode("dark");
} else {
localStorage.removeItem("mode");
localStorage.setItem("mode", "light");
setMode("Light");
}
};
return (
<div className="home">
<h2>{mode}</h2>
<button className={`button-${mode}`} onClick={handleClick}>
Click Me
</button>
</div>
);
};
export default Home;
import React from 'react'
import { func, string } from 'prop-types';
import styled from "styled-components"
const Button = styled.button`
background: ${({ theme }) => theme.background};
border: 2px solid ${({ theme }) => theme.toggleBorder};
color: ${({ theme }) => theme.text};
border-radius: 30px;
cursor: pointer;
font-size:0.8rem;
padding: 0.6rem;
}
`;
const Toggle = ({theme, toggleTheme }) => {
return (
<Button onClick={toggleTheme} >
Switch Theme
</Button>
);
};
Toggle.propTypes = {
theme: string.isRequired,
toggleTheme: func.isRequired,
}
export default Toggle;
$ npm i use-dark-mode
/* define the property */
:root {
--main-color: black;
}
/* use the property */
p {
color: var(--main-color);
}