I am not getting the desired output. I am trying to code a small task.The task is that I want to change the color of the screen background, the text and the button as shown in the uploaded image.There are total 3 files of the code. The index one, the one that contains the custom hook and the css file. I am uploading all of them. The commands change in the local storage upon pressing of "change theme" button but the changes don’t reflect on screen. I am attaching the code. Please answer if you now what’s the problem:
[enter image description here][1]index.jsx file:
import useLocalStorage from "./useLocalStorage";
export default function DarkWhiteTheme() {
const [theme, setTheme] = useLocalStorage("theme", "dark");
const handleToggleTheme = () => {
setTheme(theme === "light" ? "dark" : "light");
};
console.log(theme);
return (
<div className="light-dark-mode" data-theme={theme}>
<div className="container">
<h1>Hello World</h1>
<button onClick={handleToggleTheme} className="change-theme-button">
Change Theme
</button>
</div>
</div>
);
}
useLocalStorage File:
export default function useLocalStorage(key, defaultValue) {
const [value, setValue] = useState(() => {
let currentValue;
try {
currentValue = JSON.parse(
localStorage.getItem(key) || String(defaultValue)
);
} catch (error) {
console.log(error);
currentValue = defaultValue;
}
return currentValue;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
style.css file
:root {
--background : #ffffff
--text-primary : #000000
--button-bg: #000000
--button-text: #ffffff
}
[data-theme='dark'] {
--background: #000000
--text-primary: #ffffff
--button-bg: #ffffff
--button-text: #000000
}
.light-dark-mode {
background-color: var(--background);
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
font-size: 20px;
transition: all 0.5s;
}
.light-dark-mode .container {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
gap: 30px;
}
.light-dark-mode .container p{
color: var(--text-primary);
font-size: 40px;
margin: 0px;
}
.light-dark-mode .container button{
background-color: var(--button-bg);
border: 1px solid var(--button-bg);
color: var(--button-text);
padding: 12px;
border-radius: 8px;
font-weight: 600;
cursor: pointer;
}
.change-theme-button{
cursor: pointer;
}```
[1]: https://i.sstatic.net/ed5hnovI.png
2
Answers
instead of
try
this might help
Your code is all fine, there is nothing wrong with the
useLocalStorage
hook. The issue is with your CSS. You’ve forgotten a bunch of semi-colons.change this:
to this