When to use it#
- Use a switch for a setting that takes effect at once, with no Save or Send button, and where both on and off are safe to try. One setting per switch, each independent.
- Name the setting with a noun phrase: “Text message reminders”. It must read correctly with “on” or “off” after it. Never write the action (“Turn on reminders”), a question, or “On” and “Off”, and never change the label with the state.
- Not for an answer that is sent with a form, a declaration or a consent, or a required choice: use a Checkbox. A switch has no
required. A “Yes / No” question is a RadioGroup. - Not for a tool in a toolbar or a view you show and hide, such as “Show map”: use a Toggle. Not for an action: use a Button.
Example#
import { Field, Switch } from '@kvirn-ui/react'
import { useSwitchTexts } from './texts.ts'
export function DefaultSwitch() {
const { texts } = useSwitchTexts()
return (
<Field.Root>
<Switch name="sms" />
<Field.Label marker="none">{texts.smsReminders}</Field.Label>
</Field.Root>
)
}Use cases#
A setting that is saved at once
A switch has no Save button, so the page should say that the change is saved straight away. When the save succeeds, say nothing more: a screen reader already speaks the new state. Keep the switch enabled and focused while it saves.
Changes are saved straight away.
import { Field, Switch } from '@kvirn-ui/react'
import { useState } from 'react'
import { useSwitchTexts } from './texts.ts'
export function ControlledSetting() {
const { texts } = useSwitchTexts()
const [isOn, setIsOn] = useState(false)
return (
<Field.Root>
<Switch
name="sms"
checked={isOn}
onCheckedChange={(checked) => {
setIsOn(checked)
// A real app saves here. See "When the save fails" for the error path.
}}
/>
<Field.Label marker="none">{texts.smsReminders}</Field.Label>
<Field.HelpText>{texts.savedAtOnce}</Field.HelpText>
</Field.Root>
)
}Props in this example:
checkedon SwitchonCheckedChangeon Switch
Warning: Don't forget
Don’t disable the switch while it saves: a disabled element can lose focus (2.4.3 Focus Order). Don’t navigate, reload or move focus when it changes (3.2.2 On Input).
When the save fails
If the save fails, put the switch back to its previous state, show an error under it and announce it. Keep focus on the switch. This example always fails, to show how.
Changes are saved straight away.
import { Field, Switch, useAnnouncer } from '@kvirn-ui/react'
import { useState } from 'react'
import { useSwitchTexts } from './texts.ts'
// Stands in for a save that does not succeed, such as no connection.
function saveSetting(): Promise<void> {
return Promise.reject(new Error('offline'))
}
export function SaveFails() {
const { texts } = useSwitchTexts()
const { announce } = useAnnouncer()
const [isOn, setIsOn] = useState(false)
const [failed, setFailed] = useState(false)
return (
<Field.Root invalid={failed}>
<Switch
name="sms"
checked={isOn}
onCheckedChange={(checked) => {
setIsOn(checked)
setFailed(false)
saveSetting().catch(() => {
// Put the old state back, say why under the switch, and announce it. Focus stays.
setIsOn(!checked)
setFailed(true)
announce(texts.saveFailed)
})
}}
/>
<Field.Label marker="none">{texts.smsReminders}</Field.Label>
<Field.HelpText>{texts.savedAtOnce}</Field.HelpText>
<Field.ErrorMessage>{texts.saveFailed}</Field.ErrorMessage>
</Field.Root>
)
}Props in this example:
checkedon SwitchonCheckedChangeon Switch
Warning: Don't forget
The error is text, linked to the switch, and also announced, because it isn’t a live region (3.3.1 Error Identification, 4.1.3 Status Messages). Say what to do next (3.3.3 Error Suggestion).
A setting with a short explanation
Say in a Field.HelpText what happens when the switch is on. The screen reader reads it as the switch’s description.
We send a text message the day before your appointment.
import { Field, Switch } from '@kvirn-ui/react'
import { useSwitchTexts } from './texts.ts'
export function WithHelpText() {
const { texts } = useSwitchTexts()
return (
<Field.Root>
<Switch name="sms" />
<Field.Label marker="none">{texts.smsReminders}</Field.Label>
<Field.HelpText>{texts.smsRemindersHint}</Field.HelpText>
</Field.Root>
)
}Information: Did you know?
A help text is plain text: no link, list or heading. A screen reader reads it as one flat string, so a link or list in it would lose its meaning.
A setting that isn’t available
Disable the switch and say why in its help text, with what the person can do about it. Never put the reason in a tooltip. Tab skips a disabled switch, but a screen reader can still reach it when reading the page, and tells the user it can't be used (each screen reader words it differently). So the reason must be visible text, as here. If people need to find the setting before they can fix the reason, show the reason and a way to fix it (a link to add a mobile number) instead of a disabled switch.
Add a mobile number under Contact details to use this.
import { Field, Switch } from '@kvirn-ui/react'
import { useSwitchTexts } from './texts.ts'
export function DisabledWithReason() {
const { texts } = useSwitchTexts()
return (
<Field.Root disabled>
<Switch name="sms" />
<Field.Label marker="none">{texts.smsReminders}</Field.Label>
<Field.HelpText>{texts.noMobileHint}</Field.HelpText>
</Field.Root>
)
}In a plain form, with no form logic
Without checked the browser keeps the state, and a form submit sends the name and value of an on switch and nothing for an off one. Use defaultChecked for a switch that starts on. A setting that takes effect at once is the main use of a switch, and a plain form is the secondary case. For an answer in a submitted e-service form, use a Checkbox or a RadioGroup instead.
import { Button, Field, Switch } from '@kvirn-ui/react'
import { useState } from 'react'
import { useSwitchTexts } from './texts.ts'
export function PlainForm() {
const { texts } = useSwitchTexts()
const [sent, setSent] = useState<string | undefined>()
return (
<form
onSubmit={(event) => {
event.preventDefault()
const sms = new FormData(event.currentTarget).get('sms')
setSent(typeof sms === 'string' ? sms : texts.notChosen)
}}
>
<Field.Root>
<Switch name="sms" value="yes" defaultChecked />
<Field.Label marker="none">{texts.smsReminders}</Field.Label>
</Field.Root>
<Button type="submit" className="kv-button--primary">
{texts.send}
</Button>
{sent === undefined ? null : (
<p>
{texts.sent} {sent}
</p>
)}
</form>
)
}Props in this example:
nameon Switchvalueon SwitchdefaultCheckedon Switch
Accessibility#
What it does for you#
- APG pattern: Switch. The native form: a checkbox with
role="switch". The state is the nativechecked;aria-checkedis never written. - Deviations: none from APG. Design decisions: Enter does not toggle (APG makes it optional); no
required(a consent is a Checkbox); no strings of its own. - Native elements used:
<input type="checkbox" role="switch">, named by a<label for>(Field.Label).
A Switch is mainly a setting that takes effect at once, with no Save or Send button ("Get messages by text message"). Submitting it in a plain form also works natively, but in a public-sector e-service form prefer a Checkbox (declaration, consent) or a RadioGroup (yes or no). It is a native input, so the browser supplies the Space key, the label click, form submission, form.reset() and disabled. Switch adds the switch role, the Field's wiring, the part class and data-state. It holds no form state: pass checked and onCheckedChange from your logic, or defaultChecked and name for a plain form.
| Part | Element / role | ARIA / state | Notes |
|---|---|---|---|
| Switch | <input type="checkbox" role="switch"> | Native checked; aria-checked is never written. id, aria-describedby (help text, then the error) and aria-invalid="true" from the Field. Native disabled. data-state, data-invalid, data-disabled, data-focus-visible | Class kv-switch. Props: checked, defaultChecked, onCheckedChange(checked, { reason: 'input', event }), value, name, disabled, native input props except type, role, required, indeterminate. It must be a direct child of Field.Root, before the Field.Label |
| Field.Label | <label for>, the switch's name | The whole label is the click target (native). The name never changes with the state | A standalone Field shows "(optional)": use <Field.Label marker="none"> |
useSwitch | the same attributes, for your own elements | inputProps, isInvalid, isDisabled, isFocusVisible | Spread inputProps on your <input> |
Rules, tested in switch.test.tsx:
- A native checkbox with the switch role.
type="checkbox",role="switch", classkv-switch, noaria-checkedand noaria-required. - Named by its label. In a Field the label's
formatches the input'sid; the accessible name is the label text, with the optional marker ("(optional)" in English; each language has its own) in a standalone Field unless the label hasmarker="none". The help text describes it. - Not required.
requiredis not a prop. A required Field gives noaria-requiredand nodata-required, and warns once in development: off is a valid answer, and a consent is a Checkbox. - Optional marker. A Switch whose label shows "(optional)" warns once in development: it makes no sense for a setting. Use
<Field.Label marker="none">. data-stateischeckedorunchecked. It follows the props when controlled, and the native state after each change when not.- No form state.
defaultCheckedandnamework in a plain form: checked sendsname=value(onby default), off sends nothing,form.reset()restoresdefaultChecked. The switch never copiescheckedinto state. - Disabled. A Field's
disabledor the prop gives nativedisabledanddata-disabled. Never disable the focused switch while saving (a disabled element can lose focus, 2.4.3 Focus Order, A). - Dev warnings (once): a Switch in a Field with no Field.Label; a Switch outside a Field with no accessible name; an
idinside a Field (ignored: setcontrolIdon the Field); a required Field; an "(optional)" label.
It announces nothing.
What you need to do#
- Put the Switch directly in
Field.Root, before a<Field.Label marker="none">. - The label names the setting, a noun phrase that reads correctly with "on" or "off" after it ("Reminders by text message"). Never "On" or "Off" in it, and never a label that changes with the state.
- A switch takes effect at once: say so ("Changes are saved straight away"), keep it enabled and focused while saving, put it back and show an error if the save fails, and never navigate or move focus on change (3.2.2 On Input, A).
- A not-available switch is
disabled, with the reason in visible help text, never in a tooltip. The help text stays in itsaria-describedby. Tab skips a disabled switch (a standalone control), and Switch has no focusable disabled state. - Use a Checkbox for an answer sent with a form, a declaration or a consent, and a Toggle for a button with a direct visible effect on the page.
Warning: Don't forget
Put the switch directly in a Field, before a label with marker="none". Without a label a screen reader says only “switch” (4.1.2 Name, Role, Value).
Visual and modes#
- Focus indicator: the default theme draws an outline outside the track that follows its pill shape, at least 2px thick, with at least 3:1 contrast against its background (2.4.7 Focus Visible, AA). Keep it if you restyle.
- Target size: the track is at least 24 pixels high and wider than it is high (2.5.8 Target Size (Minimum), AA). The whole row is the click target: the label spans the row, and the row is taller in comfortable density than in compact density.
- Colour: on and off differ in the thumb's position and a tick, not only in colour (1.4.1 Use of Color, A). The edges have at least 3:1 contrast (1.4.11 Non-text Contrast, AA). Invalid is a thicker edge plus the error message. Disabled is dashed (off) or muted (on).
- forced-colors behaviour (a mode where the system chooses the colours): off uses the system's button-border colour for its edge on the field background; on is filled with the system's highlight colour and a thumb in its highlight-text colour; disabled uses the system's greyed-out text colour.
- reduced-motion behaviour: the thumb slides only when motion is allowed.
- RTL (right-to-left text): the track is at the right and the thumb moves right to left; the tick doesn't mirror.
Focus management#
- Initial focus: not moved.
- Trap: no.
- Restore to: not applicable.
- Never obscured by: the focus ring is drawn outside the track, and nothing around clips it (2.4.11 Focus Not Obscured (Minimum), AA). Consumers with a sticky header set
scroll-padding.
WCAG success criteria#
- 1.3.1 Info and Relationships (A), 4.1.2 Name, Role, Value (A): native checkbox with the switch role, label
for. - 1.4.1 Use of Color (A), 1.4.11 Non-text Contrast (AA): thumb position, the tick, the edge and the invalid width.
- 1.4.10 Reflow (AA), 1.4.12 Text Spacing (AA): the label wraps beside the track.
- 2.1.1 Keyboard (A), 2.4.3 Focus Order (A): native Tab and Space.
- 2.4.7 Focus Visible (AA), 2.4.11 Focus Not Obscured (Minimum) (AA), 2.4.13 Focus Appearance (AAA, not counted toward the AA bar).
- 2.5.3 Label in Name (A), 2.5.8 Target Size (Minimum) (AA): the visible label is the name; the row is a large click target.
- 3.2.2 On Input (A): a switch never changes context.
- 3.3.1 Error Identification (A), 3.3.2 Labels or Instructions (A): the Field's error and help text.
Keyboard#
- Focus
- native
- Selection follows focus
- n/a
- Arrows wrap
- n/a
- Shortcuts
- none
Each switch is its own Tab stop. Nothing is intercepted: Space, Enter and Tab keep their native behaviour.
| Key | Where | What happens |
|---|---|---|
| Tab | before the switch | Moves focus to the switch. Each switch is one Tab stop Test: switch.test.tsx › Tab moves to each switch, one stop each |
| Shift+Tab | on a switch | Moves focus to the previous focusable element Test: switch.test.tsx › Shift+Tab moves to the previous switch |
| Tab | disabled switch | Skips it (native disabled leaves the Tab sequence)Test: switch.test.tsx › Tab skips a disabled switch |
| Space | on a switch | Toggles it, and reports onCheckedChange (native)Test: switch.test.tsx › Space toggles the switch and reports the new state |
| Enter | on a switch | Doesn't toggle it. In a form the browser may submit it (native) Test: switch.test.tsx › Enter does not toggle the switch and is not intercepted |
| No key | label or pointer | A click on the label or the row toggles it and focuses it Test: switch.test.tsx › clicking the label text toggles the switch and focuses it |
The arrow keys, Home and End do nothing on a switch (native). The keys are the same in RTL.
API reference#
import { Field, Switch, useSwitch } from '@kvirn-ui/react'Switch
Renders <input type="checkbox" role="switch">. It takes every attribute of an <input> except type, role and required, and passes ref to it. Put it directly in a Field.Root, before the Field.Label. The label, help text and error are the Field’s parts, and the switch has no strings of its own. Write marker="none" on the Field.Label: a switch has no required state, so “(optional)” beside a setting is noise. The default theme is described on Theming.
| Prop | Type | Default | Description |
|---|---|---|---|
checked | boolean | – | Controlled: the state from your settings logic. Pair it with onCheckedChange. The switch never copies it into state of its own. |
defaultChecked | boolean | – | Uncontrolled: the browser keeps the state, and a form submit sends it. |
value | string | "on" | What a form submit sends when the switch is on. |
name | string | – | The name a form submit uses. An off switch sends nothing. |
disabled | boolean | false | Native disabled: skipped by Tab. A disabled Field disables the switch too. Never disable the switch the user has just pressed: focus is lost. |
onCheckedChange | (checked: boolean, details: SwitchChangeDetails) => void | – | Called on every change with the new state and { reason: "input", event }. It only reports. onChange still works too. |
id | string | generated | Inside a Field the Field’s id is used and yours is ignored, with a development warning. Set controlId on the Field instead. Outside a Field it is the input’s id. |
| Class or attribute | Values | Meaning |
|---|---|---|
kv-switch | always | The part class. The default theme styles it. |
role | "switch" | Set on the native checkbox, so a screen reader says “on” and “off”. |
data-state | "checked" or "unchecked" | Follows the props when controlled, and the native state after each change when not. |
data-invalid | present or absent | The Field is invalid. |
data-disabled | present or absent | The Field or the disabled prop disables it. |
data-focus-visible | present or absent | The switch has keyboard focus (:focus-visible). |
aria-invalid | "true" or absent | Set when its Field is invalid. |
aria-describedby | ids | Set for you inside a Field: the help text, then the error. Your own ids come after. |
useSwitch
Options
| Prop | Type | Default | Description |
|---|---|---|---|
checked | boolean | – | Controlled: the state from your settings logic. |
defaultChecked | boolean | – | Uncontrolled: the browser keeps the state. |
value | string | "on" | The value a form submit sends when the switch is on. |
name | string | – | The name a form submit uses. |
disabled | boolean | false | Native disabled. |
onCheckedChange | (checked: boolean, details: SwitchChangeDetails) => void | – | Called with the new checked state on every change. It only reports. |
Result
| Prop | Type | Default | Description |
|---|---|---|---|
inputProps | SwitchPartProps | – | Spread on an <input type="checkbox">: class, type, role, Field wiring, state attributes and handlers. |
isInvalid | boolean | – | Whether the Field is invalid. |
isDisabled | boolean | – | Whether the switch is disabled. |
isFocusVisible | boolean | – | Whether the switch has keyboard (:focus-visible) focus. |
Known issues#
- The thumb and tick are not tested automatically. They are drawn with CSS on the input itself. Nothing automated shows that Firefox and WebKit draw them, or that on and off differ visibly. They are reviewed by eye; check them in Windows Contrast Themes yourself. A hidden indicator element is the fallback.
data-stateafterform.reset(). For an uncontrolled switch it's updated on change events, not on a form reset. The theme styles:checked, so the look is right; read the native state, not the attribute.- Some screen readers announce
role="switch"as a checkbox or a toggle button. The state is still spoken. Check it with the screen readers your users have.
Testing#
The automated tests prove the keyboard behaviour, the names and states, that axe finds no violations in every story and theme, and, for the components they cover, that the stories hold up in forced colours, reduced motion, text spacing and a 320 pixel width. An Automated row passes on these tests alone. A Core or Release row passes only when an automated agent check and a person on the real assistive technology have both checked it. "agent-verified" means automated tests in the repository (with a virtual screen reader for the screen reader rows), not the real assistive technology.
| AT + browser + OS | Agent check | Human check | Result | Notes |
|---|---|---|---|---|
| Automated (re-runnable tests) | ||||
| axe, WCAG 2.2 A and AA, every story, 4 themes | pass | n/a | pass | switch.stories.tsx, every story, 4 themes |
| Markup and ARIA (roles, names, ids, states) | pass | n/a | pass | switch.test.tsx › renders a native <input type="checkbox" role="switch">, outside a Field; expectNoA11yViolations |
| Keyboard contract rows (Vitest browser) | pass | n/a | pass | 6 rows, each names a test (switch.test.tsx › Tab moves to each switch, one stop each) |
| Focus order and management | pass | n/a | pass | switch.test.tsx asserts focus (toHaveFocus); first rule: Tab moves to each switch, one stop each |
| Display modes (forced colours, 320px reflow, text spacing, reduced motion) | pass | n/a | pass | the four sweep projects (storybook-forced-colors, -reduced-motion, -reflow, -text-spacing), run in CI |
| Core (required for beta) | ||||
| NVDA + Chrome + Windows | pending | pending | pending | |
| VoiceOver + Safari + iOS | pending | pending | pending | |
| Release (before 1.0 and each minor) | ||||
| JAWS + Chrome + Windows | pending | pending | pending | |
| TalkBack + Chrome + Android | pending | pending | pending | |
| VoiceOver + Safari + macOS | pending | pending | pending |
What to check#
With a screen reader and the keyboard, try:
- Tab to the switch: the label, "switch", on or off and the help text are read.
- Press Space: the new state is read.
- Enter in a form does not toggle the switch.
- Click the label: the switch toggles and takes focus.
- A failed save shows and announces the error.
- In a high-contrast theme the focus ring and the on and off looks differ.