I've just created a theme handler with React.js.
Could my Theme
component be polished and improved a bit ?
function Theme() {
const [checkbox, setCheckbox] = React.useState(
JSON.parse(localStorage.getItem("configuration"))?.dark_theme ?? true
);
React.useEffect(() => (
!checkbox
? document.body.setAttribute('data-theme', 'light')
: document.body.removeAttribute('data-theme'),
setToLocalStorage({ dark_theme: checkbox }, "configuration") //memorization
), [checkbox])
return (
<div className="theme">
βοΈ
<label htmlFor="theme-checkbox">
<input
type="checkbox"
id="theme-checkbox"
defaultChecked={checkbox}
onChange={() => setCheckbox(!checkbox)}
/>
<span className="slidebar"></span>
</label>
π
</div>
)
}
Thanks for your help
1 Answer 1
Names! Calling a variable that represents whether the theme is dark mode or not
checkbox
is pretty confusing. Why am I setting a local storage value tocheckbox
? It took me a moment to unwind that.The comma operator inside the
useEffect
seems odd to me, but maybe that's how it's being done these days. I'd probably just braces around the function body and use regular JS statements.The line
setToLocalStorage({ dark_theme: checkbox }, "configuration")
will work fine for now, but as soon as you introduce more configurations it will (mysteriously) wipe out all the other ones every time this checkbox is changed.