{/* Copyright 2020 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License. */}

import {Layout} from '@react-spectrum/docs';
export default Layout;

import docs from 'docs:react-aria-components';
import typesDocs from 'docs:@react-types/shared/src/events.d.ts';
import {PropTable, HeaderInfo, TypeLink, PageDescription, StateTable, ContextTable} from '@react-spectrum/docs';
import styles from '@react-spectrum/docs/src/docs.css';
import packageData from 'react-aria-components/package.json';
import Anatomy from '/packages/react-aria/docs/switch/anatomy.svg';
import ChevronRight from '@spectrum-icons/workflow/ChevronRight';
import {Divider} from '@react-spectrum/divider';
import {ExampleCard} from '@react-spectrum/docs/src/ExampleCard';
import {ExampleList} from '@react-spectrum/docs/src/ExampleList';
import {Keyboard} from '@react-spectrum/text';
import {StarterKits} from '@react-spectrum/docs/src/StarterKits';

---
category: Forms
keywords: [switch, input, checkbox, aria]
type: component
---

# Switch

<PageDescription>{docs.exports.Switch.description}</PageDescription>

<HeaderInfo
  packageData={packageData}
  componentNames={['Switch']}
  sourceData={[
    {type: 'W3C', url: 'https://www.w3.org/WAI/ARIA/apg/patterns/switch/'}
  ]} />

## Example

```tsx example
import {Switch} from 'react-aria-components';

<Switch>
  <div className="indicator" />
  Low power mode
</Switch>
```

<details>
  <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>

```css
@import "@react-aria/example-theme";

.react-aria-Switch {
  display: flex;
  /* This is needed so the HiddenInput is positioned correctly */
  position: relative;
  align-items: center;
  gap: 0.571rem;
  font-size: 1.143rem;
  color: var(--text-color);
  forced-color-adjust: none;

  .indicator {
    width: 2rem;
    height: 1.143rem;
    border: 2px solid var(--border-color);
    background: var(--background-color);
    border-radius: 1.143rem;
    transition: all 200ms;

    &:before {
      content: '';
      display: block;
      margin: 0.143rem;
      width: 0.857rem;
      height: 0.857rem;
      background: var(--highlight-background);
      border-radius: 16px;
      transition: all 200ms;
    }
  }

  &[data-pressed] .indicator {
    border-color: var(--border-color-pressed);

    &:before {
      background: var(--highlight-background-pressed);
    }
  }

  &[data-selected] {
    .indicator {
      border-color: var(--highlight-background);
      background: var(--highlight-background);

      &:before {
        background: var(--field-background);
        transform: translateX(100%);
      }
    }

    &[data-pressed] {
      .indicator {
        border-color: var(--highlight-background-pressed);
        background: var(--highlight-background-pressed);
      }
    }
  }

  &[data-focus-visible] .indicator {
    outline: 2px solid var(--focus-ring-color);
    outline-offset: 2px;
  }
}
```

</details>

## Features

There is no native HTML element with switch styling. `<input type="checkbox">` is the closest semantically, but isn't styled or exposed to assistive technology as a switch. `Switch` helps achieve accessible switches that can be styled as needed.

* **Styleable** – Hover, press, keyboard focus, and selection states are provided for easy styling. These states only apply when interacting with an appropriate input device, unlike CSS pseudo classes.
* **Accessible** – Uses a visually hidden `<input>` element with `role="switch"` under the hood, which also enables HTML form integration and autofill. A label element is built-in to ensure the switch is usable with assistive technologies.
* **Cross-browser** – Mouse, touch, keyboard, and focus interactions are normalized to ensure consistency across browsers and devices.

## Anatomy

<Anatomy />

A switch consists of a visual selection indicator and a label. Users may click or touch a switch
to toggle the selection state, or use the <Keyboard>Tab</Keyboard> key to navigate to it and the <Keyboard>Space</Keyboard> key to toggle it.

In most cases, switches should have a visual label. If the switch does not have a visible label,
an `aria-label` or `aria-labelledby` prop must be passed instead to identify the element to assistive
technology.

## Examples

<ExampleList tag="switch" />

## Starter kits

To help kick-start your project, we offer starter kits that include example implementations of all React Aria components with various styling solutions. All components are fully styled, including support for dark mode, high contrast mode, and all UI states. Each starter comes with a pre-configured [Storybook](https://storybook.js.org/) that you can experiment with, or use as a starting point for your own component library.

<StarterKits component="switch" />

## Reusable wrappers

If you will use a Switch in multiple places in your app, you can wrap all of the pieces into a reusable component. This way, the DOM structure, styling code, and other logic are defined in a single place and reused everywhere to ensure consistency.

This example wraps `Switch` and all of its children together into a single component.

```tsx example export=true
import type {SwitchProps} from 'react-aria-components';

interface MySwitchProps extends Omit<SwitchProps, 'children'> {
  children: React.ReactNode
}

function MySwitch({children, ...props}: MySwitchProps) {
  return (
    <Switch {...props}>
      <div className="indicator" />
      {children}
    </Switch>
  );
}

<MySwitch>Wi-Fi</MySwitch>
```

## Value

### Default value

Switches are not selected by default. The `defaultSelected` prop can be used to set the default state.

```tsx example
<MySwitch defaultSelected>Wi-Fi</MySwitch>
```

### Controlled value

The `isSelected` prop can be used to make the selected state controlled. The `onChange` event is fired when the user presses the switch, and receives the new value.

```tsx example
function Example() {
  let [selected, setSelected] = React.useState(false);

  return (
    <>
      <MySwitch isSelected={selected} onChange={setSelected}>Low power mode</MySwitch>
      <p>{selected ? 'Low' : 'High'} power mode active.</p>
    </>
  );
}
```

### HTML forms

Switch supports the `name` and `value` props for integration with HTML forms.

```tsx example
<MySwitch name="power" value="low">Low power mode</MySwitch>
```

## Disabled

Switches can be disabled using the `isDisabled` prop.

```tsx example
<MySwitch isDisabled>Airplane Mode</MySwitch>
```

<details>
  <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>

```css
.react-aria-Switch {
  &[data-disabled] {
    color: var(--text-color-disabled);

    .indicator {
      border-color: var(--border-color-disabled);

      &:before {
        background: var(--border-color-disabled);
      }
    }
  }
}
```

</details>

### Read only

The `isReadOnly` prop makes the selection immutable. Unlike `isDisabled`, the Switch remains focusable.
See the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/readonly) for more information.

```tsx example
<MySwitch isSelected isReadOnly>Bluetooth</MySwitch>
```

## Props

<PropTable component={docs.exports.Switch} links={docs.links} />

## Styling

React Aria components can be styled in many ways, including using CSS classes, inline styles, utility classes (e.g. Tailwind), CSS-in-JS (e.g. Styled Components), etc. By default, all components include a builtin `className` attribute which can be targeted using CSS selectors. These follow the `react-aria-ComponentName` naming convention.

```css
.react-aria-Switch {
  /* ... */
}
```

A custom `className` can also be specified on any component. This overrides the default `className` provided by React Aria with your own.

```jsx
<Switch className="my-switch">
  {/* ... */}
</Switch>
```

In addition, some components support multiple UI states (e.g. focused, placeholder, readonly, etc.). React Aria components expose states using data attributes, which you can target in CSS selectors. For example:
```css
.react-aria-Switch[data-pressed] {
  /* ... */
}
```

The `className` and `style` props also accept functions which receive states for styling. This lets you dynamically determine the classes or styles to apply, which is useful when using utility CSS libraries like [Tailwind](https://tailwindcss.com/).

```jsx
<Switch className={({isPressed}) => isPressed ? 'bg-gray-700' : 'bg-gray-600'} />
```

Render props may also be used as children to alter what elements are rendered based on the current state. For example, you could render an extra element when the switch is selected.

```jsx
<Switch>
  {({isSelected}) => (
    <>
      {isSelected && <OnIcon />}
      Wi-Fi
    </>
  )}
</Switch>
```

The states, selectors, and render props for `Switch` are documented below.

<StateTable properties={docs.exports.SwitchRenderProps.properties} />

## Advanced customization

### Contexts

All React Aria Components export a corresponding context that can be used to send props to them from a parent element. This enables you to build your own compositional APIs similar to those found in React Aria Components itself. You can send any prop or ref via context that you could pass to the corresponding component. The local props and ref on the component are merged with the ones passed via context, with the local props taking precedence (following the rules documented in [mergeProps](mergeProps.html)).

<ContextTable components={['Switch']} docs={docs} />

This example shows a `SwitchDescription` component that accepts a switch in its children and renders a description element below it. It uses the [useId](useId.html) hook to generate a unique id for the description, and associates it with the switch via the `aria-describedby` attribute passed to the `SwitchContext` provider.

```tsx example
import {SwitchContext} from 'react-aria-components';
import {useId} from 'react-aria';

interface SwitchDescriptionProps {
  children?: React.ReactNode,
  description?: string
}

function SwitchDescription({children, description}: SwitchDescriptionProps) {
  let descriptionId = useId();
  return (
    <div>
      {/*- begin highlight -*/}
      <SwitchContext.Provider value={{'aria-describedby': descriptionId}}>
      {/*- end highlight -*/}
        {children}
      </SwitchContext.Provider>
      <small id={descriptionId}>{description}</small>
    </div>
  );
}

<SwitchDescription description="Connected to 'Starbucks Wifi'.">
  <MySwitch defaultSelected>Wi-Fi</MySwitch>
</SwitchDescription>
```

### Hooks

If you need to customize things further, such as accessing internal state or customizing DOM structure, you can drop down to the lower level Hook-based API. See [useSwitch](useSwitch.html) for more details.
