1
\$\begingroup\$

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

asked Feb 7, 2022 at 14:02
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$
  • 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 to checkbox? 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.

answered Feb 7, 2022 at 23:47
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.