ProPro components are coming soon. Stay tuned!

Switch Component

The Switch component provides a toggle switch for boolean inputs. It's perfect for settings, preferences, and on/off states.

Basic Usage

import { Switch } from 'nebula-ui';
import { useState } from 'react';
 
export default function Example() {
  const [enabled, setEnabled] = useState(false);
  
  return (
    <Switch 
      checked={enabled}
      onCheckedChange={setEnabled}
      label="Enable notifications"
    />
  );
}

With Label

Add a label to describe what the switch controls:

<Switch 
  checked={darkMode}
  onCheckedChange={setDarkMode}
  label="Dark mode"
/>

Controlled Component

Use controlled state for the switch:

const [enabled, setEnabled] = useState(false);
 
<Switch 
  checked={enabled}
  onCheckedChange={setEnabled}
  label="Enable feature"
/>

Uncontrolled Component

You can also use it without a label:

<Switch 
  checked={isEnabled}
  onCheckedChange={(checked) => console.log(checked)}
/>

Disabled State

Disable the switch to prevent interactions:

<Switch 
  checked={false}
  disabled
  label="Disabled switch"
/>
 
<Switch 
  checked={true}
  disabled
  label="Disabled checked"
/>

Full Width

Make the switch span the full width:

<Switch 
  checked={enabled}
  onCheckedChange={setEnabled}
  label="Full width switch"
  fullWidth
/>

Props

PropTypeDefaultDescription
checkedbooleanfalseWhether the switch is checked
onCheckedChange(checked: boolean) => void-Callback when switch state changes
disabledbooleanfalseDisable the switch
labelstring-Label text
fullWidthbooleanfalseMakes switch full width

Accessibility

The Switch component is fully accessible:

  • Keyboard navigation support (Space/Enter to toggle)
  • Proper ARIA attributes (role="switch", aria-checked)
  • Screen reader support
  • Focus management

Examples

Settings Panel

<div className="space-y-4">
  <Switch 
    checked={notifications}
    onCheckedChange={setNotifications}
    label="Email notifications"
  />
  <Switch 
    checked={darkMode}
    onCheckedChange={setDarkMode}
    label="Dark mode"
  />
  <Switch 
    checked={autoSave}
    onCheckedChange={setAutoSave}
    label="Auto-save"
  />
</div>

Feature Toggle

<Switch 
  checked={featureEnabled}
  onCheckedChange={(checked) => {
    setFeatureEnabled(checked);
    // Additional logic here
  }}
  label="Enable new feature"
/>

Best Practices

  1. Always provide a label to describe what the switch controls
  2. Use for boolean settings - switches are ideal for on/off states
  3. Provide immediate feedback - changes should take effect immediately
  4. Group related switches together in a settings panel
  5. Use disabled state when the switch cannot be changed

Was this page helpful?

Let us know if this documentation helped you.