# Switch

## Introduction

The Switch component is a toggle input that lets users turn an option on or off. It is built on Joy UI's Switch and provides a variety of sizes, colors, variants, and decorator slots for icons or text.

Switches are best suited for binary settings that take effect immediately, such as enabling notifications, toggling dark mode, or activating a feature. Unlike a checkbox (which is often part of a form submission), a switch communicates an instant state change.

```tsx
<Switch />
```

| Field          | Description | Default |
| -------------- | ----------- | ------- |
| variant        | —           | —       |
| color          | —           | —       |
| size           | —           | —       |
| startDecorator | —           | —       |
| endDecorator   | —           | —       |
| checked        | —           | —       |

## Usage

```tsx
import { Switch } from '@ceed/cds';

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

  return <Switch checked={enabled} onChange={(e) => setEnabled(e.target.checked)} />;
}
```

## With Labels

Use `FormControl` with `FormLabel` and `FormHelperText` to provide a label and description alongside the switch. The `orientation="horizontal"` layout places the label on the left and the switch on the right.

```tsx
<FormControl
    orientation="horizontal"
    sx={{
      width: 300,
      justifyContent: "space-between"
    }}
  >
    <div>
      <FormLabel>Show captions</FormLabel>
      <FormHelperText
        sx={{
          mt: 0
        }}
      >
        All languages available.
      </FormHelperText>
    </div>
    <Switch
      checked={checked}
      onChange={(e) => setChecked(e.target.checked)}
      color={checked ? "success" : "neutral"}
      variant={checked ? "solid" : "outlined"}
      endDecorator={checked ? "On" : "Off"}
      slotProps={{
        endDecorator: {
          sx: {
            minWidth: 24
          }
        }
      }}
    />
  </FormControl>
```

## Inline Labels

For simpler cases, wrap the switch inside a `Typography` component rendered as a `<label>`. This connects the text and switch semantically without requiring a `FormControl`.

```tsx
<Typography
    component="label"
    endDecorator={
      <Switch
        sx={{
          ml: 1
        }}
      />
    }
  >
    Turn alarm on
  </Typography>
```

## With Decorators

Use `startDecorator` and `endDecorator` to place icons or text around the switch. This is particularly useful for theme toggles or any context where visual cues reinforce the on/off meaning.

```tsx
<Switch
    color={dark ? "primary" : "danger"}
    slotProps={{
      input: {
        "aria-label": "dark mode"
      }
    }}
    startDecorator={
      <LightModeIcon
        sx={(theme) => ({
          color: dark ? "currentColor" : "var(--ceed-palette-danger-solidBg)"
        })}
      />
    }
    endDecorator={
      <DarkModeIcon
        sx={(theme) => ({
          color: dark ? "var(--ceed-palette-primary-solidBg)" : "currentColor"
        })}
      />
    }
    checked={dark}
    onChange={(event) => setDark(event.target.checked)}
  />
```

## Track Children

Display text or symbols inside the switch track using `slotProps.track.children`. This provides an always-visible label (e.g., "On" / "Off" or "I" / "0") directly on the track.

```tsx
<Stack direction="row" spacing={4}>
    <Switch
      {...args}
      slotProps={{
        track: {
          children: (
            <React.Fragment>
              <Typography
                component="span"
                level="inherit"
                sx={{
                  ml: "10px"
                }}
              >
                On
              </Typography>
              <Typography
                component="span"
                level="inherit"
                sx={{
                  mr: "8px"
                }}
              >
                Off
              </Typography>
            </React.Fragment>
          )
        }
      }}
      sx={{
        "--Switch-thumbSize": "27px",
        "--Switch-trackWidth": "64px",
        "--Switch-trackHeight": "31px"
      }}
    />
    <Switch
      color="success"
      slotProps={{
        track: {
          children: (
            <React.Fragment>
              <span>I</span>
              <span>0</span>
            </React.Fragment>
          ),
          sx: {
            justifyContent: "space-around"
          }
        }
      }}
      sx={{
        "--Switch-thumbSize": "27px",
        "--Switch-trackWidth": "52px",
        "--Switch-trackHeight": "31px"
      }}
    />
  </Stack>
```

## Thumb Children

Place an icon inside the switch thumb using `slotProps.thumb.children`. This is useful for adding a small visual indicator that moves with the toggle.

```tsx
<Switch
    size="lg"
    slotProps={{
      input: {
        "aria-label": "Dark mode"
      },
      thumb: {
        children: <DarkModeIcon fontSize="inherit" />
      }
    }}
    sx={{
      "--Switch-thumbSize": "16px"
    }}
  />
```

## All Variants Overview

A comprehensive view of all color and decoration combinations.

```tsx
<Stack direction="row" spacing={4}>
    {([undefined, "primary", "warning", "success", "danger", "neutral"] as const).map((color) => (
      <Stack key={color} spacing={2}>
        <Switch color={color} />
        <Switch color={color} checked />
        <Switch color={color} startDecorator={<LightModeIcon />} endDecorator={<DarkModeIcon />} />
        <Switch
          color={color}
          slotProps={{
            input: {
              "aria-label": "Dark mode"
            },
            thumb: {
              children: <DarkModeIcon fontSize="inherit" />
            },
            track: {
              children: (
                <React.Fragment>
                  <span>I</span>
                  <span>0</span>
                </React.Fragment>
              ),
              sx: {
                justifyContent: "space-around"
              }
            }
          }}
          sx={{
            "--Switch-thumbSize": "27px",
            "--Switch-trackWidth": "52px",
            "--Switch-trackHeight": "31px"
          }}
        />
        <Typography
          component="label"
          startDecorator={
            <Switch
              sx={{
                ml: 1
              }}
              color={color}
            />
          }
        >
          Label
        </Typography>
      </Stack>
    ))}
  </Stack>
```

## Common Use Cases

### Settings Panel

```tsx
function SettingsPanel() {
  const [notifications, setNotifications] = useState(true);
  const [autoSave, setAutoSave] = useState(false);

  return (
    <Stack spacing={3}>
      <FormControl orientation="horizontal" sx={{ width: 400, justifyContent: 'space-between' }}>
        <div>
          <FormLabel>Notifications</FormLabel>
          <FormHelperText sx={{ mt: 0 }}>Receive alerts when new messages arrive.</FormHelperText>
        </div>
        <Switch
          checked={notifications}
          onChange={(e) => setNotifications(e.target.checked)}
          color={notifications ? 'success' : 'neutral'}
        />
      </FormControl>

      <FormControl orientation="horizontal" sx={{ width: 400, justifyContent: 'space-between' }}>
        <div>
          <FormLabel>Auto Save</FormLabel>
          <FormHelperText sx={{ mt: 0 }}>Automatically save your work every 30 seconds.</FormHelperText>
        </div>
        <Switch checked={autoSave} onChange={(e) => setAutoSave(e.target.checked)} />
      </FormControl>
    </Stack>
  );
}
```

### Theme Toggle

```tsx
function ThemeToggle() {
  const [darkMode, setDarkMode] = useState(false);

  return (
    <Switch
      checked={darkMode}
      onChange={(e) => setDarkMode(e.target.checked)}
      color={darkMode ? 'primary' : 'danger'}
      startDecorator={<LightModeIcon />}
      endDecorator={<DarkModeIcon />}
      slotProps={{
        input: { 'aria-label': 'Toggle dark mode' },
      }}
    />
  );
}
```

### Feature Flag with Status Text

```tsx
function FeatureToggle() {
  const [betaEnabled, setBetaEnabled] = useState(false);

  return (
    <FormControl orientation="horizontal" sx={{ justifyContent: 'space-between' }}>
      <FormLabel>Enable Beta Features</FormLabel>
      <Switch
        checked={betaEnabled}
        onChange={(e) => setBetaEnabled(e.target.checked)}
        color="warning"
        endDecorator={betaEnabled ? 'On' : 'Off'}
      />
    </FormControl>
  );
}
```

## Best Practices

1. **Use switches for immediate effects**: Switches should apply their change instantly without requiring a "Save" button. If the setting requires a form submission, use a checkbox instead.

```tsx
// ✅ Immediate effect -- toggling notifications on/off
<Switch
  checked={notificationsEnabled}
  onChange={(e) => toggleNotifications(e.target.checked)}
/>

// ❌ Deferred effect requiring form submission -- use Checkbox instead
<form onSubmit={handleSubmit}>
  <Switch checked={agreed} onChange={(e) => setAgreed(e.target.checked)} />
  <Button type="submit">Save</Button>
</form>
```

2. **Always provide a label**: Every switch needs a visible text label or an `aria-label` so users understand what it controls.

```tsx
// ✅ Clear label via FormControl
<FormControl orientation="horizontal">
  <FormLabel>Email Notifications</FormLabel>
  <Switch checked={enabled} onChange={handleChange} />
</FormControl>

// ❌ No label -- unclear what the switch does
<Switch checked={enabled} onChange={handleChange} />
```

3. **Use semantic colors to reinforce meaning**: Apply `color="success"` for active/enabled states and `color="danger"` for risky toggles. Avoid using color as the sole indicator -- pair it with text.

```tsx
// ✅ Color + text indicator
<Switch
  checked={enabled}
  onChange={handleChange}
  color={enabled ? 'success' : 'neutral'}
  endDecorator={enabled ? 'On' : 'Off'}
/>
```

4. **Handle async operations gracefully**: If toggling triggers an API call, disable the switch and show a processing indicator until the operation completes.

5. **Group related switches logically**: Place related switches under a shared heading and use consistent spacing to create a scannable settings layout.

## Props and Customization

### Key Props

| Prop             | Type                                                           | Default     | Description                           |
| ---------------- | -------------------------------------------------------------- | ----------- | ------------------------------------- |
| `checked`        | `boolean`                                                      | -           | Whether the switch is on (controlled) |
| `defaultChecked` | `boolean`                                                      | `false`     | Initial state (uncontrolled)          |
| `onChange`       | `(event: ChangeEvent<HTMLInputElement>) => void`               | -           | Callback when the state changes       |
| `disabled`       | `boolean`                                                      | `false`     | Disables the switch                   |
| `readOnly`       | `boolean`                                                      | `false`     | Makes the switch read-only            |
| `color`          | `'primary' \| 'neutral' \| 'danger' \| 'success' \| 'warning'` | `'neutral'` | Color scheme when checked             |
| `size`           | `'sm' \| 'md' \| 'lg'`                                         | `'md'`      | Switch size                           |
| `variant`        | `'solid' \| 'soft' \| 'outlined' \| 'plain'`                   | `'solid'`   | Visual style                          |
| `startDecorator` | `ReactNode`                                                    | -           | Content rendered before the switch    |
| `endDecorator`   | `ReactNode`                                                    | -           | Content rendered after the switch     |
| `sx`             | `SxProps`                                                      | -           | Custom styles using the MUI system    |

> **Note**: Switch also accepts all Joy UI Switch props and Framer Motion props.

## Accessibility

- **Role and state**: The Switch renders an `<input type="checkbox" role="switch">` with `aria-checked` reflecting the current state. Screen readers announce it as a switch, not a checkbox.
- **Keyboard interaction**: `Tab` moves focus to the switch. `Space` toggles the state. No additional key bindings are needed.
- **Labeling**: Use `FormLabel`, a `<label>` wrapper (via `Typography component="label"`), or `slotProps.input['aria-label']` to provide an accessible name. Use `aria-describedby` to connect supplementary descriptions.
- **Visual indicators beyond color**: Do not rely solely on color to communicate state. Use `endDecorator` text (e.g., "On" / "Off") or track children to ensure the state is perceivable without color vision.
