# Switch Field (/components/forms/switch-field)



Use `SwitchField` for a setting someone turns on or off. Pass `label` to name the setting, and
`description` to clarify what it changes.

apps/docs/src/examples/switch-field/basic.tsx

```tsx
import { SwitchField } from '@luke-ui/react/switch-field';

export default () => {
	return <SwitchField description="Example description" label="Example switch" />;
};
```

## Best practices [#best-practices]

Use a switch for an immediate change, such as a preference that saves straight away. Use a
[`CheckboxField`](/components/forms/checkbox-field) for a choice that someone submits with a form,
such as accepting terms.

## Labels [#labels]

Every `SwitchField` has a visible `label`. The label sits inside a native `<label>`, so pass textual
content only. Place links and buttons next to the switch. Inline typography such as `Strong` works
inside the label. Set `slot={null}` on a `Text` you place there, as the
[Checkbox primitive](/components/primitives/checkbox#text-in-the-label) describes.

When another part of the layout draws the visible label, such as a settings row, compose the
[Switch primitive](/components/primitives/switch) and name the control with `aria-labelledby`.

## States [#states]

Use `defaultSelected` for an uncontrolled initial value, or pair `isSelected` with `onChange` when
application state owns the setting. Set `isReadOnly` to keep the current value while a change is
saving.

apps/docs/src/examples/switch-field/states.tsx

```tsx
import { SwitchField } from '@luke-ui/react/switch-field';
import { Comparison, ComparisonItem } from '#docs';

export default () => {
	return (
		<Comparison>
			<ComparisonItem label="Off">
				<SwitchField label="Example switch" />
			</ComparisonItem>
			<ComparisonItem label="On">
				<SwitchField defaultSelected label="Example switch" />
			</ComparisonItem>
			<ComparisonItem label="Disabled">
				<SwitchField isDisabled label="Example switch" />
			</ComparisonItem>
			<ComparisonItem label="Disabled and on">
				<SwitchField defaultSelected isDisabled label="Example switch" />
			</ComparisonItem>
			<ComparisonItem label="Invalid">
				<SwitchField
					errorMessage="Turn on this example switch to continue."
					label="Example switch"
				/>
			</ComparisonItem>
		</Comparison>
	);
};
```

## Size [#size]

Use `size` to change the switch control. It does not change the label typography. `medium` is the
default.

apps/docs/src/examples/switch-field/sizes.tsx

```tsx
import { SwitchField } from '@luke-ui/react/switch-field';
import { Comparison, ComparisonItem } from '#docs';

export default () => {
	return (
		<Comparison>
			<ComparisonItem label="Small">
				<SwitchField defaultSelected label="Example switch" size="small" />
			</ComparisonItem>
			<ComparisonItem label="Medium">
				<SwitchField defaultSelected label="Example switch" size="medium" />
			</ComparisonItem>
			<ComparisonItem label="Large">
				<SwitchField defaultSelected label="Example switch" size="large" />
			</ComparisonItem>
		</Comparison>
	);
};
```

## Validation [#validation]

Pass `errorMessage` for an error you already have, such as one from your server. A non-empty message
marks the switch invalid. Set `isRequired` only when the switch must be on before a form submits,
and pass `validate` for a custom rule. Read [Validation](/docs/validation) for where messages come
from and how to write them.

A required switch shows a marker after its `label`. Read
[Required fields](/components/forms/text-input-field#required-fields) for both `necessityIndicator`
values.

## IDs and refs [#ids-and-refs]

`id`, `className`, and `ref` target the root element. `inputId` and `inputRef` target the input.

## Form values [#form-values]

Pass `name` so the switch joins `FormData` while it is on. Pass `value` to set the submitted value,
and `form` to associate a switch with a `<form>` it does not sit inside.

## Accessibility [#accessibility]

A switch has the `switch` role, so assistive technology announces it as on or off. Space toggles it
from the keyboard. Disabled switches cannot receive focus. Read-only switches remain focusable, so
someone who uses a keyboard or assistive technology can still perceive their state.

## API [#api]

### SwitchFieldProps

Props for `SwitchField`.

`SwitchFieldProps` also accepts compatible DOM and ARIA attributes and event handlers for its rendered element.

| Prop                  | Type        | Description                                                                                                             |
| --------------------- | ----------- | ----------------------------------------------------------------------------------------------------------------------- |
| `aria-describedby?`   | `string`    | Identifies the element (or elements) that describes the object.                                                         |
| `aria-details?`       | `string`    | Identifies the element (or elements) that provide a detailed, extended description for the object.                      |
| `aria-errormessage?`  | `string`    | Identifies the element that provides an error message for the object.                                                   |
| `onKeyDown?`          | `function`  | Handler that is called when a key is pressed.                                                                           |
| `onKeyUp?`            | `function`  | Handler that is called when a key is released.                                                                          |
| `onFocus?`            | `function`  | Handler that is called when the element receives focus.                                                                 |
| `onBlur?`             | `function`  | Handler that is called when the element loses focus.                                                                    |
| `onFocusChange?`      | `function`  | Handler that is called when the element's focus status changes.                                                         |
| `onPress?`            | `function`  | Handler that is called when the press is released over the target.                                                      |
| `onPressStart?`       | `function`  | Handler that is called when a press interaction starts.                                                                 |
| `onPressEnd?`         | `function`  | Handler that is called when a press interaction ends, either over the target or when the pointer leaves the target.     |
| `onPressChange?`      | `function`  | Handler that is called when the press state changes.                                                                    |
| `onPressUp?`          | `function`  | Handler that is called when a press is released over the target, regardless of whether it started on the target or not. |
| `autoFocus?`          | `union`     | Whether the element should receive focus on render.                                                                     |
| `className?`          | `union`     | Class name for the root element.                                                                                        |
| `defaultSelected?`    | `union`     | Initial selection state for an uncontrolled switch.                                                                     |
| `form?`               | `string`    | The `<form>` element to associate the input with, by id.                                                                |
| `id?`                 | `string`    | Element id for the root element. Use `inputId` for the input.                                                           |
| `inputId?`            | `string`    | Element id for the input and the `for` of a `FieldLabel` in the root. Defaults to a generated id.                       |
| `inputRef?`           | `union`     | Forwarded to the underlying `<input type="checkbox" role="switch">` element.                                            |
| `isDisabled?`         | `union`     | Whether the switch is disabled.                                                                                         |
| `isReadOnly?`         | `union`     | Whether the switch can be read but not changed.                                                                         |
| `isRequired?`         | `union`     | Whether the switch must be on before the form can submit.                                                               |
| `isSelected?`         | `union`     | Whether the switch is on.                                                                                               |
| `name?`               | `string`    | The name of the input, used when submitting an HTML form.                                                               |
| `onChange?`           | `function`  | Called when the switch turns on or off.                                                                                 |
| `ref?`                | `union`     | Forwarded to the root element.                                                                                          |
| `size?`               | `union`     | Visual size of the switch control. Default: `'medium'`                                                                  |
| `validate?`           | `function`  | Custom validation function run against the selection. Return a message, or `true`/`null` when valid.                    |
| `validationBehavior?` | `union`     | When native HTML form validation runs. Default: `'native'`                                                              |
| `value?`              | `string`    | The value submitted with an HTML form when the switch is on.                                                            |
| `description?`        | `ReactNode` | Supporting text shown beneath the switch label.                                                                         |
| `errorMessage?`       | `ReactNode` | Validation message for a controlled error. A non-empty message marks the field invalid.                                 |
| `label`               | `union`     | Visible label. Pass non-empty, textual, non-interactive content. Place links and buttons outside the switch.            |
| `necessityIndicator?` | `union`     | How a required switch is marked. Default: `'icon'`                                                                      |
