DEV Community

Discussion on: component #5 - Switch

Collapse
 
aut0poietic profile image
Jer

Nice work @oieeaaaa !

On thing you might want to keep in mind is that anything set to display: none is not available to screen readers or via the tab order -- so for those people that need a screen reader or navigate via keyboard can't interact with your switch. visibility:hidden will do the same thing.

For some unsolicited advice: One of the ways I've made this work (in a switch component in fact) is to give the label position:relative, then position your switch UI (that is, the track, knob etc) as a child of the label (and thus a direct sibling of the input). Then apply a relative position to both the input and switch ui, and position the input beneath the switch UI.

<label class="switch-container">
   <input type="checkbox" value="is_dark" />
   <div class="switch-ui">...</div>
</label>

This structure enables some seriously cool CSS using the adjacent sibling selector. A partial example:

input[type="checkbox"]:checked + .switch-ui {
  // your checked styles here...
}

input[type="checkbox"]:focus + .switch-ui {
  // your focused styles here...
}

Those two selectors effectively say "When the input checkbox is checked, give the adjacent sibling of the input that has the class switch-ui these styles." The second statement does the same when the checkbox is focused.

The benefit is that this is much less work for both you and your javascript. You just define a few states as classes and all the browser handles the rest. All your React class has to do is maintain the checked state of the input itself.

Again, this is nice work. Keep it up!

Collapse
 
oieeaaaa profile image
Joe

Hey @Jer, Thanks for this great advice.

I just have one question though. If you place the <input type="checkbox" /> besides <div className="switch-ui"></div> would it still maintain it's width and height causing a weird spacing between the label and the <div className="switch-ui"></div>?

Hmmmm, This is probably the reason why I use display: none;. hahaha

Collapse
 
aut0poietic profile image
Jer

I didn't describe the technique too well. I've been intending to do a toggle control in my Web Component experiments. If you like, share one this weekend so you can see what I mean.

Something I want to make sure I am getting across is that you're doing great work! I don't want to give the impression I'm saying "This is the way to do it" -- I'm absolutely not. This is just how I do things and you might see a useful technique or two. I guess I spend too much of my time teaching my devs; Hard habit to break ;-)

Thread Thread
 
aut0poietic profile image
Jer

Hopefully this does a better job of explaining what I meant. :)

codepen.io/aut0poietic/pen/EqaGgw