Skip to content
TopClass UI

Switch

An on and off switch for a setting that takes effect at once. Its thumb travels the right way in right-to-left layouts.

client - size not measured yet

Switch

client - size not measured yet

An on and off switch for a setting that takes effect at once. Its thumb travels the right way in right-to-left layouts.

Install

Try it

size
invalid

The code

switch.tsx
import { Switch } from 'topclassui/switch'

<div className="flex items-center gap-2">
  <Switch id="switch-playground" defaultChecked />
  <label htmlFor="switch-playground" className="text-sm text-body">Weekly digest</label>
</div>

The xs and sm switches still grow to a 44px target under a touch pointer, so the thumb stays easy to tap.

Every state

7 states

Import from the package

topclassui/switch
import { Switch } from 'topclassui/switch'

Install once:npm i topclassui@beta zod

Examples

  • For a setting that takes effect as it is turned on or off. For a choice the form sends later, a Checkbox reads better.
  • In a form, off sends nothing and on sends on, before the page hydrates and after. An unchecked value makes an off switch send a string of its own.
  • A form reset brings the switch back to its default, on screen and in the form.
  • Switch draws no label of its own: write a <label htmlFor> that points at its id.
  • size="custom" draws no track size: give the track one from your own CSS.
basic
form
unchecked-value
sizes
In Arabic, right to left

Props

The props of Switch
PropTypeDefaultLimitsDescription
aria-labelstring--The name read out when no visible label names the control.
aria-labelledbystring--The id of the visible text that names the control.
idstring--The id a <label htmlFor> points at.
classNamestring--Merged last, so a consumer class wins a conflict with the switch's own.
invalidbooleanfalse-Marks the value as wrong: sets aria-invalid, and the line of the track turns to danger and thickens.
refRef<HTMLButtonElement>--The root element, which is a <button>.
sizexs | sm | md | lg | xl | custom"md"-The toggle scale of the track and its thumb; custom emits no size classes.

Keyboard and accessibility

The keyboard of Switch
KeysWhat it does
TabMoves the focus to the switch; a disabled switch is skipped.
SpaceEnterTurn the switch on or off.
  • A name is required: id for a <label htmlFor>, or aria-label, or aria-labelledby. The root is a <button role="switch">.
  • The target is 24px, 44px under a touch pointer, whatever size draws: the focus ring is around the track.
  • invalid sets aria-invalid, and the line of the track turns to danger and thickens.

Right to left

The thumb starts at the right and slides left when the switch is on, with no code change.

Server and client

A client component: it renders on the server and hydrates in the browser.

Files: index.tsx, client.tsx.

On the chip: client - size not measured yet.