Switch
Headless switch primitive for creating accessible on/off settings. Renders a
single focusable element with role="switch"; you compose the visual
track/thumb in your own DOM and combine it with <Field> for labels,
descriptions, and validation wiring.
Live Demo
function SwitchDemo() { const [checked, setChecked] = React.useState(true); return ( <Field className='switch-field'> <Field.Label className='switch-label'>Notifications</Field.Label> <Switch className='switch-control' checked={checked} onChange={setChecked} > <span className='switch-track' aria-hidden='true'> <span className='switch-thumb' /> </span> </Switch> </Field> ); }
Switch is a single polymorphic element (default <button>) that emits
data-state="checked|unchecked". The visual track/thumb live in your DOM as
ordinary children, and <Field> provides the label/description wiring.
Features
- ✅ Single accessible control with
role="switch"and full ARIA wiring - ✅ Controlled (
checked) and uncontrolled (defaultChecked) modes - ✅ Native form submission via hidden
input[type="checkbox"](name,value,form,required) - ✅ Inherits
disabled,readOnly,required, andinvalidfrom an ancestor<Field>; direct props win - ✅ Render-prop children expose state for derived UI
- ✅ Polymorphic via the
asprop
Import
import { Switch } from '@turkish-technology/spar';
// Low-level hook for fully custom anatomy
import { useSwitch } from '@turkish-technology/spar';
Anatomy
The Switch is a single interactive element. Compose surrounding layout, label,
and description with <Field>; place the visual track and thumb inside the
switch as plain children so they can be styled freely.
Structure
<Field>
<Field.Label>…</Field.Label>
<Switch>
<span className="track" aria-hidden="true">
<span className="thumb" />
</span>
</Switch>
<Field.Description>…</Field.Description>
</Field>
Data flow:
Switchowns the controlled/uncontrolled checked state and toggles on click,Space, andEnter.- When nested inside
<Field>,disabled,readOnly,required, andinvalidare inherited automatically; props on<Switch>always take precedence. aria-labelledbyandaria-describedbyare wired toField.LabelandField.Description/Field.ErrorMessagewhen a Field ancestor is present.- When
nameis set,Switchrenders a synchronized hiddeninput[type="checkbox"]for native form submission.
Code Examples
Basic Usage
function BasicSwitch() {
return (
<Field>
<Field.Label>Enable notifications</Field.Label>
<Switch defaultChecked>
<span className="track" aria-hidden="true">
<span className="thumb" />
</span>
</Switch>
</Field>
);
}
Controlled Switch
function ControlledSwitch() {
const [enabled, setEnabled] = React.useState(false);
return (
<Field>
<Field.Label>Dark mode</Field.Label>
<Switch checked={enabled} onChange={setEnabled} />
<Field.Description>
{enabled ? 'Theme is dark' : 'Theme is light'}
</Field.Description>
</Field>
);
}
Uncontrolled Switch
function UncontrolledSwitch() {
return (
<Switch
defaultChecked={false}
onChange={checked => console.log('Changed to:', checked)}
/>
);
}
Form Integration
Provide name and optional value. The hidden input[type="checkbox"] is
rendered automatically and submits alongside the rest of the form.
function FormExample() {
return (
<form
onSubmit={event => {
event.preventDefault();
const formData = new FormData(event.currentTarget);
console.log(formData.get('notifications'), formData.get('darkMode'));
}}
>
<Field>
<Field.Label>Notifications</Field.Label>
<Switch name="notifications" defaultChecked />
</Field>
<Field>
<Field.Label>Dark mode</Field.Label>
<Switch name="darkMode" value="enabled" defaultChecked />
</Field>
<button type="submit">Save</button>
</form>
);
}
Inheriting Field State
When wrapped in <Field>, the Switch picks up disabled, readOnly,
required, and invalid automatically.
<Field disabled>
<Field.Label>Disabled (off)</Field.Label>
<Switch />
</Field>
<Field readOnly>
<Field.Label>Read-only (on)</Field.Label>
<Switch defaultChecked />
</Field>
<Field required invalid>
<Field.Label>Required</Field.Label>
<Switch />
<Field.ErrorMessage>You must enable this option.</Field.ErrorMessage>
</Field>
Render-prop Children
Pass a function as children to derive UI from current state without subscribing externally.
<Switch defaultChecked>
{({ checked }) => (
<span className="track" aria-hidden="true" data-on={checked || undefined}>
<span className="thumb" />
</span>
)}
</Switch>
Custom Element
<Switch as="div" defaultChecked>
<span className="track" aria-hidden="true">
<span className="thumb" />
</span>
</Switch>
When as is not a native button, aria-disabled is emitted instead of the
disabled HTML attribute.
Fully Custom Anatomy with useSwitch
When you need a totally different DOM shape, use the low-level hook instead of
<Switch>.
import { useSwitch } from '@turkish-technology/spar';
function CustomSwitch() {
const { checked, switchProps, hiddenInputProps } = useSwitch({
defaultChecked: true,
});
return (
<label>
<span>Wi-Fi</span>
<button {...switchProps}>{checked ? 'on' : 'off'}</button>
<input {...hiddenInputProps} name="wifi" />
</label>
);
}
API Reference
Switch
| Name | Type | Default | Description |
|---|---|---|---|
as? | React.ElementType | "button" | Element or component to render as |
checked? | boolean | undefined | Controlled checked state |
defaultChecked? | boolean | false | Initial checked state in uncontrolled mode |
onChange? | (checked: boolean) => void | undefined | Called when checked state changes |
disabled? | boolean | inherited | Prevents interaction; inherited from <Field> when omitted |
readOnly? | boolean | inherited | Keeps focus, blocks state changes; inherited from <Field> |
required? | boolean | inherited | Sets aria-required and hidden-input required; inherited from <Field> |
invalid? | boolean | inherited | Sets aria-invalid and data-invalid; inherited from <Field> |
name? | string | undefined | Hidden input name. When set, the hidden form input is rendered |
value? | string | "on" | Hidden input value when checked |
form? | string | undefined | Associates the hidden input with an external form id |
autoFocus? | boolean | false | Focuses the control on mount |
id? | string | generated | Overrides the control id; ignored when inside <Field> (the field's id is used) |
children? | React.ReactNode | ((state: SwitchRenderProps) => React.ReactNode) | undefined | Visual content (track/thumb) or render-prop function |
...props | ComponentPropsWithRef<"button"> | - | Other native props for the polymorphic element |
SwitchRenderProps
| Property | Type | Description |
|---|---|---|
checked | boolean | Whether the switch is currently checked |
setChecked | (checked: boolean) => void | Function to programmatically set the checked state |
disabled | boolean | Resolved disabled state |
readOnly | boolean | Resolved read-only state |
required | boolean | Resolved required state |
invalid | boolean | Resolved invalid state |
isFocused | boolean | Whether the switch currently has focus |
isHovered | boolean | Whether the switch is being hovered |
isPressed | boolean | Whether the switch is being pressed |
HTML Attributes
| Attribute | Value | Purpose |
|---|---|---|
role | "switch" | Applies switch semantics |
aria-checked | boolean | Reflects checked state |
aria-labelledby | string | Wired to Field.Label when inside <Field> |
aria-describedby | string | Wired to Field.Description / ErrorMessage |
aria-readonly | true | Present when read-only |
aria-required | true | Present when required |
aria-invalid | true | Present when invalid |
data-switch | "" | Marker attribute |
data-state | "checked" | "unchecked" | Checked state token |
data-checked | "" | Present when checked |
data-disabled | "" | Present when disabled |
data-readonly | "" | Present when read-only |
data-required | "" | Present when required |
data-invalid | "" | Present when invalid |
data-focus | "" | Present while focused |
data-hover | "" | Present while hovered |
data-active | "" | Present while pressed |
Hidden Input
Switch renders a hidden input[type="checkbox"] only when name is provided.
| Attribute | Value | Purpose |
|---|---|---|
type | "checkbox" | Enables native form submission semantics |
name | string | Form field name |
value | string | Submitted value when checked |
form | string | Associates input to external form id |
required | boolean | Participates in native form validation |
checked | boolean | Mirrors switch checked state |
disabled | boolean | Mirrors disabled state |
tabIndex | -1 | Keeps hidden input out of tab sequence |
aria-hidden | true | Hides input from assistive tech tree |
Keyboard Interactions
| Key | Action | Notes |
|---|---|---|
Tab | Moves focus to switch | Skipped when disabled is true |
Shift + Tab | Moves focus backward | Standard reverse tab navigation |
Space | Toggles checked state | No state change when disabled or readOnly is true |
Enter | Toggles checked state | No state change when disabled or readOnly is true |