Toggle Switch

EasyReact Components15 min6 tests

Build an accessible on/off toggle switch button that reflects its state via aria-pressed and visible ON/OFF text, flipping each time it is clicked.

Create an accessible toggle switch as a single React component.

The switch is a real <button> that controls a boolean on/off state. It must start in the OFF position. Each click flips the state: OFF becomes ON, ON becomes OFF.

Accessibility requirements:

  • The button uses the aria-pressed attribute to reflect the current state: "true" when ON, "false" when OFF.
  • The button has a stable, descriptive accessible name (e.g. an aria-label like "Toggle switch") so it can be found regardless of the current state text.
  • The current state is shown as visible text: the literal word ON when on, and OFF when off. This live text should be exposed via role="status" so assistive tech announces changes.

This is a foundational controlled-UI pattern: a single piece of boolean state, a click handler that flips it, and an accessible rendering of that state. No timers, no randomness — pure deterministic state.

Requirements

  • Render a real <button> element with a stable accessible name (e.g. aria-label="Toggle switch") that does not change with state.
  • The switch starts in the OFF state on initial render.
  • Clicking the button toggles the state: OFF -> ON, then ON -> OFF on the next click.
  • Set aria-pressed="false" when OFF and aria-pressed="true" when ON on the button.
  • Show the current state as visible text "OFF" when off and "ON" when on.
  • Expose the current state text through an element with role="status" so it is announced to assistive technology.
Hints (4)
  1. Use a single boolean state value: const [on, setOn] = useState(false). false means OFF, which satisfies the 'starts OFF' requirement.
  2. The button's onClick should call setOn(prev => !prev) so each click flips the current value rather than reading a possibly-stale closure.
  3. Keep the button's aria-label constant (like 'Toggle switch'). Put the ON/OFF word inside a separate element with role="status" so the button can still be queried by its fixed name.
  4. aria-pressed must be the boolean state itself (React renders it as the strings 'true'/'false'), and the status text is simply on ? 'ON' : 'OFF'.

Topics

  • React
  • React Components

Asked at

Postman · Zoho · Amazon · Uber · Flipkart · Zomato

Join Us
blur