DEV Community

Discussion on: Toggle Dark Mode in React

Collapse
 
overtureweb profile image
Overture Web

This was super helpful, I love it! Thanks for taking the time to go through it. I found a place to simplify, rather than use a ternary operator that renders one of two input elements you could use an equality check expression as the checkbox input’s “checked” property.

<input type="checkbox" id="toggle" className="toggle--checkbox" onClick={handleOnClick} checked={togClass === “light”} />
Enter fullscreen mode Exit fullscreen mode
Collapse
 
abbeyperini profile image
Abbey Perini • Edited

Ah, but the reason "I couldn’t get defaultChecked to work how I wanted, so I replaced the unchecked with this conditional rendering ternary operator (conditional operator):" is the togClass doesn't just depend on whether the checkbox is checked. It also depends on the theme set in localStorage. Otherwise, the user could have light mode enabled by default or have set the theme to light mode and reloaded. Then the "checked=false" state will not match the current set theme and you'll see a moon on a light background. I was trying to tell the element to be checked or unchecked using a conditional in the defaultChecked property in the element, which made React yell about an uncontrolled element. The ternary operator renders 1 element either in the checked or unchecked state, which will not cause React to yell about it being uncontrolled.

Collapse
 
abbeyperini profile image
Abbey Perini

You were totally right! I just didn't understand what you were saying. You can see the updated logic here: dev.to/abbeyperini/an-accessible-d...