Skip to main content

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​

JavaScript
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, and invalid from an ancestor <Field>; direct props win
  • ✅ Render-prop children expose state for derived UI
  • ✅ Polymorphic via the as prop

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.

Parts
FieldGeneric wrapper that owns ARIA relationships (label, description, error)
Field.LabelVisible label, linked via aria-labelledby
SwitchThe interactive control with role="switch"
Visual trackDecorative child you own, styled via data-state
Visual thumbDecorative child you own, styled via data-state

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:

  • Switch owns the controlled/uncontrolled checked state and toggles on click, Space, and Enter.
  • When nested inside <Field>, disabled, readOnly, required, and invalid are inherited automatically; props on <Switch> always take precedence.
  • aria-labelledby and aria-describedby are wired to Field.Label and Field.Description / Field.ErrorMessage when a Field ancestor is present.
  • When name is set, Switch renders a synchronized hidden input[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​

NameTypeDefaultDescription
as?React.ElementType"button"Element or component to render as
checked?booleanundefinedControlled checked state
defaultChecked?booleanfalseInitial checked state in uncontrolled mode
onChange?(checked: boolean) => voidundefinedCalled when checked state changes
disabled?booleaninheritedPrevents interaction; inherited from <Field> when omitted
readOnly?booleaninheritedKeeps focus, blocks state changes; inherited from <Field>
required?booleaninheritedSets aria-required and hidden-input required; inherited from <Field>
invalid?booleaninheritedSets aria-invalid and data-invalid; inherited from <Field>
name?stringundefinedHidden input name. When set, the hidden form input is rendered
value?string"on"Hidden input value when checked
form?stringundefinedAssociates the hidden input with an external form id
autoFocus?booleanfalseFocuses the control on mount
id?stringgeneratedOverrides the control id; ignored when inside <Field> (the field's id is used)
children?React.ReactNode | ((state: SwitchRenderProps) => React.ReactNode)undefinedVisual content (track/thumb) or render-prop function
...propsComponentPropsWithRef<"button">-Other native props for the polymorphic element

SwitchRenderProps​

PropertyTypeDescription
checkedbooleanWhether the switch is currently checked
setChecked(checked: boolean) => voidFunction to programmatically set the checked state
disabledbooleanResolved disabled state
readOnlybooleanResolved read-only state
requiredbooleanResolved required state
invalidbooleanResolved invalid state
isFocusedbooleanWhether the switch currently has focus
isHoveredbooleanWhether the switch is being hovered
isPressedbooleanWhether the switch is being pressed

HTML Attributes​

AttributeValuePurpose
role"switch"Applies switch semantics
aria-checkedbooleanReflects checked state
aria-labelledbystringWired to Field.Label when inside <Field>
aria-describedbystringWired to Field.Description / ErrorMessage
aria-readonlytruePresent when read-only
aria-requiredtruePresent when required
aria-invalidtruePresent 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.

AttributeValuePurpose
type"checkbox"Enables native form submission semantics
namestringForm field name
valuestringSubmitted value when checked
formstringAssociates input to external form id
requiredbooleanParticipates in native form validation
checkedbooleanMirrors switch checked state
disabledbooleanMirrors disabled state
tabIndex-1Keeps hidden input out of tab sequence
aria-hiddentrueHides input from assistive tech tree

Keyboard Interactions​

KeyActionNotes
TabMoves focus to switchSkipped when disabled is true
Shift + TabMoves focus backwardStandard reverse tab navigation
SpaceToggles checked stateNo state change when disabled or readOnly is true
EnterToggles checked stateNo state change when disabled or readOnly is true