I've been struggling to achieve the desired outcome while working on a small coding task. The goal is to modify the color of the screen background, text, and button as illustrated in the uploaded image. I have three code files for this task - index, the custom hook, and the CSS file. Despite updating the commands in local storage upon clicking the "change theme" button, the changes are not reflecting on the screen. Could someone please review the code and suggest a solution?
[see attached image][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;
}