DEV Community

Discussion on: Toggle Dark Mode in React

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.