## Import

```jsx
import { Switch } from "@cfa/react-core";
```

## Live Editor

```jsx
<Switch>Label</Switch>
```

## Guidelines

### When to use

- Switch is for an on/off option that takes effect immediately.

### Do

- Phrase labels as switchable nouns, such as `Email notifications`, not as verbs.
- Add a description when the label alone cannot provide enough context.
- In switch groups, prefer a vertical layout for easier reading.

### Avoid

- Using Switch for an opt-in choice submitted with a form. Use Checkbox.
- Using Switch where the action needs confirmation. Use Button with a confirmation Modal.

## Examples

### Description

Use the `description` prop to add a description to the switch. The description will be displayed below the switch.

```jsx
<Switch description="Description">Label</Switch>
```

### Invalid

The `isInvalid` prop applies an error outline to the switch.

```jsx
<div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
  <Switch isInvalid>Enable notifications</Switch>
  <Switch isInvalid defaultSelected>
    Enable notifications
  </Switch>
</div>
```

### Error Message

Use `errorMessage` with `isInvalid` to display validation text below the switch.

```jsx
<Switch isInvalid errorMessage="You must enable this setting to continue">
  Enable notifications
</Switch>
```

### AutoFocus

Use the `autoFocus` prop to automatically focus the switch when it is mounted.

```jsx
<Switch autoFocus>Label</Switch>
```

### Readonly

The `isReadOnly` prop makes the switch read-only, preventing user interaction.

```jsx
<Switch isReadOnly>Label</Switch>
```

### Disabled

The `isDisabled` prop disables the switch, preventing user interaction.

```jsx
<Switch isDisabled>Label</Switch>
```

### Default Selected

Use the `defaultSelected` prop to set the initial state of the switch. The switch will be checked by default.

```jsx
<Switch defaultSelected>Label</Switch>
```

### Controlled

To use the `Switch` in a controlled state, you can use the combination of `isSelected` which is a `boolean` and `onChange` which accepts a function.

```jsx
function ControlledExample() {
  const [isSelected, setIsSelected] = React.useState(false);

  return (
    <>
      <Switch
        isSelected={isSelected}
        onChange={(value) => {
          setIsSelected(value);
        }}
      >
        Label
      </Switch>
      <p style={{ marginTop: "1rem" }}>
        {isSelected ? "The switch is selected." : "The switch is not selected."}
      </p>
    </>
  );
}
```

### Label Position

The `labelPosition` prop allows you to change the position of the label. The default is `right`.

```jsx
<div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
  <Switch labelPosition="right">Right Label</Switch>
  <Switch labelPosition="left">Left Label</Switch>
  <Switch labelPosition="top">Top Label</Switch>
</div>
```

### Native HTML Forms

The `Switch` component can be used in native HTML forms. The `name` prop is required for the switch to be submitted with the form.

```jsx
function NativeFormExample() {
  const [isSelected, setIsSelected] = React.useState(false);

  return (
    <form
      style={{ display: "flex", flexDirection: "column", gap: 16, maxWidth: 200 }}
      onSubmit={(e) => {
        e.preventDefault();
        alert("Form submitted");
      }}
    >
      <Switch
        name="switch"
        isSelected={isSelected}
        onChange={(value) => {
          setIsSelected(value);
        }}
      >
        Label
      </Switch>
      <Button type="submit">Submit</Button>
    </form>
  );
}
```

## Props

### Switch

| Name | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| children\* | `ReactNode` | - | The label of the switch. |
| description | `string` | - | Helper text for the switch. |
| errorMessage | `string \ | ((validation: ValidationResult) => string)` | - | Custom error message to display when the switch is invalid. |
| inputRef | `RefObject<HTMLInputElement>` | - | React 19 only |
| labelPosition | `"left" \ | "right" \ | "top" \ | null` | - | - |
| ref | `Ref<HTMLDivElement>` | - | React 19 only |
| aria-controls | `string` | - | Identifies the element (or elements) whose contents or presence are controlled by the current element. |
| 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. |
| aria-label | `string` | - | Defines a string value that labels the current element. |
| aria-labelledby | `string` | - | Identifies the element (or elements) that labels the current element. |
| autoFocus | `boolean` | - | Whether the element should receive focus on render. |
| className | `ClassNameOrFunction<SwitchFieldRenderProps>` | `'react-aria-SwitchField'` | The CSS \[className]\(https\://developer.mozilla.org/en-US/docs/Web/API/Element/className) for the element. A function may be provided to compute the class based on component state. |
| defaultSelected | `boolean` | - | Whether the element should be selected (uncontrolled). |
| dir | `string` | - | - |
| excludeFromTabOrder | `boolean` | - | Whether to exclude the element from the sequential tab order. If true, the element will not be focusable via the keyboard by tabbing. This should be avoided except in rare scenarios where an alternative means of accessing the element or its functionality via the keyboard is available. |
| form | `string` | - | The \`\<form>\` element to associate the input with. The value of this attribute must be the id of a \`\<form>\` in the same document. See \[MDN]\(https\://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input#form). |
| hidden | `boolean` | - | - |
| id | `string` | - | The element's unique identifier. See \[MDN]\(https\://developer.mozilla.org/en-US/docs/Web/HTML/Global\_attributes/id). |
| inert | `boolean` | - | - |
| isDisabled | `boolean` | - | Whether the input is disabled. |
| isInvalid | `boolean` | - | Whether the input value is invalid. |
| isReadOnly | `boolean` | - | Whether the input can be selected but not changed by the user. |
| isRequired | `boolean` | - | Whether user input is required on the input before form submission. |
| isSelected | `boolean` | - | Whether the element should be selected (controlled). |
| lang | `string` | - | - |
| name | `string` | - | The name of the input element, used when submitting an HTML form. See \[MDN]\(https\://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#htmlattrdefname). |
| onAnimationEnd | `AnimationEventHandler<HTMLDivElement>` | - | - |
| onAnimationEndCapture | `AnimationEventHandler<HTMLDivElement>` | - | - |
| onAnimationIteration | `AnimationEventHandler<HTMLDivElement>` | - | - |
| onAnimationIterationCapture | `AnimationEventHandler<HTMLDivElement>` | - | - |
| onAnimationStart | `AnimationEventHandler<HTMLDivElement>` | - | - |
| onAnimationStartCapture | `AnimationEventHandler<HTMLDivElement>` | - | - |
| onAuxClick | `MouseEventHandler<HTMLDivElement>` | - | - |
| onAuxClickCapture | `MouseEventHandler<HTMLDivElement>` | - | - |
| onBlur | `((e: FocusEvent<Element, Element>) => void)` | - | Handler that is called when the element loses focus. |
| onChange | `((isSelected: boolean) => void)` | - | Handler that is called when the element's selection state changes. |
| onClick | `((e: MouseEvent<FocusableElement, MouseEvent>) => void)` | - | \*\*Not recommended – use \`onPress\` instead.\*\* \`onClick\` is an alias for \`onPress\` provided for compatibility with other libraries. \`onPress\` provides additional event details for non-mouse interactions. |
| onClickCapture | `MouseEventHandler<HTMLDivElement>` | - | - |
| onContextMenu | `MouseEventHandler<HTMLDivElement>` | - | - |
| onContextMenuCapture | `MouseEventHandler<HTMLDivElement>` | - | - |
| onDoubleClick | `MouseEventHandler<HTMLDivElement>` | - | - |
| onDoubleClickCapture | `MouseEventHandler<HTMLDivElement>` | - | - |
| onFocus | `((e: FocusEvent<Element, Element>) => void)` | - | Handler that is called when the element receives focus. |
| onFocusChange | `((isFocused: boolean) => void)` | - | Handler that is called when the element's focus status changes. |
| onGotPointerCapture | `PointerEventHandler<HTMLDivElement>` | - | - |
| onGotPointerCaptureCapture | `PointerEventHandler<HTMLDivElement>` | - | - |
| onKeyDown | `((e: KeyboardEvent) => void)` | - | Handler that is called when a key is pressed. |
| onKeyUp | `((e: KeyboardEvent) => void)` | - | Handler that is called when a key is released. |
| onLostPointerCapture | `PointerEventHandler<HTMLDivElement>` | - | - |
| onLostPointerCaptureCapture | `PointerEventHandler<HTMLDivElement>` | - | - |
| onMouseDown | `MouseEventHandler<HTMLDivElement>` | - | - |
| onMouseDownCapture | `MouseEventHandler<HTMLDivElement>` | - | - |
| onMouseEnter | `MouseEventHandler<HTMLDivElement>` | - | - |
| onMouseLeave | `MouseEventHandler<HTMLDivElement>` | - | - |
| onMouseMove | `MouseEventHandler<HTMLDivElement>` | - | - |
| onMouseMoveCapture | `MouseEventHandler<HTMLDivElement>` | - | - |
| onMouseOut | `MouseEventHandler<HTMLDivElement>` | - | - |
| onMouseOutCapture | `MouseEventHandler<HTMLDivElement>` | - | - |
| onMouseOver | `MouseEventHandler<HTMLDivElement>` | - | - |
| onMouseOverCapture | `MouseEventHandler<HTMLDivElement>` | - | - |
| onMouseUp | `MouseEventHandler<HTMLDivElement>` | - | - |
| onMouseUpCapture | `MouseEventHandler<HTMLDivElement>` | - | - |
| onPointerCancel | `PointerEventHandler<HTMLDivElement>` | - | - |
| onPointerCancelCapture | `PointerEventHandler<HTMLDivElement>` | - | - |
| onPointerDown | `PointerEventHandler<HTMLDivElement>` | - | - |
| onPointerDownCapture | `PointerEventHandler<HTMLDivElement>` | - | - |
| onPointerEnter | `PointerEventHandler<HTMLDivElement>` | - | - |
| onPointerLeave | `PointerEventHandler<HTMLDivElement>` | - | - |
| onPointerMove | `PointerEventHandler<HTMLDivElement>` | - | - |
| onPointerMoveCapture | `PointerEventHandler<HTMLDivElement>` | - | - |
| onPointerOut | `PointerEventHandler<HTMLDivElement>` | - | - |
| onPointerOutCapture | `PointerEventHandler<HTMLDivElement>` | - | - |
| onPointerOver | `PointerEventHandler<HTMLDivElement>` | - | - |
| onPointerOverCapture | `PointerEventHandler<HTMLDivElement>` | - | - |
| onPointerUp | `PointerEventHandler<HTMLDivElement>` | - | - |
| onPointerUpCapture | `PointerEventHandler<HTMLDivElement>` | - | - |
| onPress | `((e: PressEvent) => void)` | - | Handler that is called when the press is released over the target. |
| onPressChange | `((isPressed: boolean) => void)` | - | Handler that is called when the press state changes. |
| onPressEnd | `((e: PressEvent) => void)` | - | Handler that is called when a press interaction ends, either over the target or when the pointer leaves the target. |
| onPressStart | `((e: PressEvent) => void)` | - | Handler that is called when a press interaction starts. |
| onPressUp | `((e: PressEvent) => void)` | - | Handler that is called when a press is released over the target, regardless of whether it started on the target or not. |
| onScroll | `UIEventHandler<HTMLDivElement>` | - | - |
| onScrollCapture | `UIEventHandler<HTMLDivElement>` | - | - |
| onTouchCancel | `TouchEventHandler<HTMLDivElement>` | - | - |
| onTouchCancelCapture | `TouchEventHandler<HTMLDivElement>` | - | - |
| onTouchEnd | `TouchEventHandler<HTMLDivElement>` | - | - |
| onTouchEndCapture | `TouchEventHandler<HTMLDivElement>` | - | - |
| onTouchMove | `TouchEventHandler<HTMLDivElement>` | - | - |
| onTouchMoveCapture | `TouchEventHandler<HTMLDivElement>` | - | - |
| onTouchStart | `TouchEventHandler<HTMLDivElement>` | - | - |
| onTouchStartCapture | `TouchEventHandler<HTMLDivElement>` | - | - |
| onTransitionCancel | `TransitionEventHandler<HTMLDivElement>` | - | - |
| onTransitionCancelCapture | `TransitionEventHandler<HTMLDivElement>` | - | - |
| onTransitionEnd | `TransitionEventHandler<HTMLDivElement>` | - | - |
| onTransitionEndCapture | `TransitionEventHandler<HTMLDivElement>` | - | - |
| onTransitionRun | `TransitionEventHandler<HTMLDivElement>` | - | - |
| onTransitionRunCapture | `TransitionEventHandler<HTMLDivElement>` | - | - |
| onTransitionStart | `TransitionEventHandler<HTMLDivElement>` | - | - |
| onTransitionStartCapture | `TransitionEventHandler<HTMLDivElement>` | - | - |
| onWheel | `WheelEventHandler<HTMLDivElement>` | - | - |
| onWheelCapture | `WheelEventHandler<HTMLDivElement>` | - | - |
| render | `DOMRenderFunction<"div", SwitchFieldRenderProps>` | - | Overrides the default DOM element with a custom render function. This allows rendering existing components with built-in styles and behaviors such as router links, animation libraries, and pre-styled components.&#xA;&#xA;Requirements:&#xA;&#xA;- You must render the expected element type (e.g. if \`\<button>\` is expected, you cannot render an \`\<a>\`).&#xA;- Only a single root DOM element can be rendered (no fragments).&#xA;- You must pass through props and ref to the underlying DOM element, merging with your own prop as appropriate. |
| slot | `string \ | null` | - | A slot name for the component. Slots allow the component to receive props from a parent component. An explicit \`null\` value indicates that the local props completely override all props received from a parent. |
| style | `StyleOrFunction<SwitchFieldRenderProps>` | - | The inline \[style]\(https\://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style) for the element. A function may be provided to compute the style based on component state. |
| suppressHydrationWarning | `boolean` | - | A React-only flag that suppresses the warning React normally logs when an element's server-rendered content doesn't match the client render during hydration. See \[React docs]\(https\://react.dev/reference/react-dom/client/hydrateRoot#suppressing-unavoidable-hydration-mismatch-errors). |
| translate | `"no" \ | "yes"` | - | - |
| validate | `((value: boolean) => true \ | ValidationError \ | null)` | - | A function that returns an error message if a given value is invalid. Validation errors are displayed to the user when the form is submitted if \`validationBehavior="native"\`. For realtime validation, use the \`isInvalid\` prop instead. |
| validationBehavior | `"aria" \ | "native"` | `'native'` | Whether to use native HTML form validation to prevent form submission when the value is missing or invalid, or mark the field as required or invalid via ARIA. |
| value | `string` | - | The value of the input element, used when submitting an HTML form. See \[MDN]\(https\://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#htmlattrdefvalue). |