Toggle SwitchLoading saved progress…

Toggle Switch

Build an on/off toggle switch as a single React component. It's the simplest piece of stateful UI there is — one boolean — but doing it right means the visual state, the ARIA state, and the label all read from that single source of truth, and the control is a real role="switch" button, not a bare <div>.

Task

The starter App.tsx renders the switch in its off state. Make it interactive:

  1. Hold the state. Track an on boolean with useState(false).
  2. Flip on click. The switch button toggles on each time it's clicked.
  3. Reflect it three ways. When on is true: add the on class to the switch (the knob slides via CSS), set aria-checked={on}, and show On (else Off) in the status line.

Examples

  • The page loads with the knob on the left, a grey track, and "Off" below. Clicking the switch slides the knob right, turns the track green, and shows "On".
  • Clicking again flips it back to off. Each click toggles.
  • A screen reader announces the control as a switch that is "on" or "off", because role="switch" + aria-checked are wired to the same state.

Notes

  • One boolean, three effects. Don't track the class, the aria value, and the label separately — derive all three from on.
  • Use a real switch role. The control is a <button role="switch"> with aria-checked; that's the accessible pattern (keyboard and screen-reader support come for free from the button).
  • The knob animation is pure CSS. .switch.on .knob { transform: translateX(...) } handles the slide — you only toggle the class.
  • Styling (dark theme, track, knob) is already in styles.css; focus on the state.
Loading editor…
Loading preview…