nqui
Components

Switch

A toggle switch component for boolean inputs

Switch

The Switch component is a toggle switch for boolean inputs. Built on Radix UI primitives for full accessibility and smooth animations.

Installation

npm install @nqlib/nqui

Import

import { Switch } from '@nqlib/nqui';

Basic Usage

import { Switch, Label } from '@nqlib/nqui';

export default function Example() {
  return (
    <div className="flex items-center gap-2">
      <Switch id="notifications" />
      <Label htmlFor="notifications">Enable notifications</Label>
    </div>
  );
}

Examples

Basic Switch

Controlled Switch

Default Checked

Disabled States

Switch Group

With Label

Always pair switches with labels for accessibility:

import { Switch, Label } from '@nqlib/nqui';

<div className="flex items-center gap-2">
  <Switch id="notifications" />
  <Label htmlFor="notifications">Enable notifications</Label>
</div>

Controlled Switch

Use controlled state for programmatic control:

const [enabled, setEnabled] = useState(false);

<Switch checked={enabled} onCheckedChange={setEnabled} />

Uncontrolled Switch

Use defaultChecked for uncontrolled state:

<Switch defaultChecked />

Disabled State

<Switch disabled />
<Switch disabled defaultChecked />

Props

PropTypeDefaultDescription
checkedboolean-Controlled checked state
defaultCheckedbooleanfalseUncontrolled default checked state
onCheckedChange(checked: boolean) => void-Callback when checked state changes
disabledbooleanfalseWhether the switch is disabled
requiredbooleanfalseWhether the switch is required
namestring-Form field name
valuestring-Form field value
classNamestring-Additional CSS classes

Styling

Switches use the following design tokens:

  • Track (unchecked): bg-input
  • Track (checked): bg-primary
  • Thumb: bg-background with shadow
  • Border: border-transparent
  • Focus ring: ring-ring with ring-offset-background
  • Disabled: opacity-50 with cursor-not-allowed

Accessibility

  • Full keyboard navigation support
  • ARIA attributes for screen readers
  • Focus management with visible focus rings
  • Proper label association
  • Disabled state handling
  • Toggle semantics

Best Practices

  1. Always use labels: Pair every switch with a label for accessibility
  2. Use for boolean toggles: Switches are ideal for on/off settings
  3. Provide clear labels: Use descriptive labels that indicate what the switch controls
  4. Handle disabled states: Clearly indicate when switches are disabled
  5. Consider grouping: Group related switches together

Next Steps