跳转到内容

Switch

Switches toggle the state of a single setting on or off.

Introduction

Switches are very commonly used for adjusting settings on mobile. The option that the switch controls, as well as the state it's in, should be made clear from the corresponding inline label.

<Switch />

Playground

Component

After installation, you can start building with this component using the following basic elements:

import Switch from '@mui/joy/Switch';

export default function MyApp() {
  return <Switch />;
}

Controlled

To create a controlled switch, use the checked and onChange props.

Label

Use the Switch component inside the Typography's endDecorator prop for having labels.

Decorators

To insert icon decorators, use the startDecorator and/or endDecorator props.

Track child

Target the track's children using the componentsProps prop to display a text inside of it.

OnOff

Thumb child

Simmilarly to the above, target the thumb's children to display icons inside of it.

CSS Variables

Play around with all the CSS variables available in the switch component to see how the design changes.

You can use those to customize the component on both the sx prop and the theme.

<Switch />

CSS Variables

px

Accessibility

Here are a few tips to make sure you have an accessible switch component:

  • The Switch will render with the checkbox role as opposed to switch. This is mainly because the latter isn't widely supported yet. However, if you believe your audience will support it, make sure to test with assistive technology. Use the componentProps prop to change the role:

    <Switch componentsProps={{ input: { role: 'switch' } }}>
    
  • Every form control component should have proper labels. This includes radio buttons, checkboxes, and switches. In most cases, this is done using the <label> element.

    • If a label can't be applied, make sure to add an attribute (e.g. aria-label, aria-labelledby, title) to the input slot inside the componentProps prop.
    <Switch value="checkedA" componentsProps={{ 'aria-label': 'Switch A' }} />
    

Common examples

Material Design

You can also find the Material Design switch design, out of the box, in Material UI's documentation.

Fluent

Here's how you'd customize Joy UI's switch to make it look like Microsoft's Fluent UI:

  • Unchecked state: outlined variant and neutral color.
  • Checked state: solid variant and primary color.

iOS

Note how we've used the :active pseudo-class to replicate the small thumb size increase, which happens when you press and holder the switch.

Strapi

Chakra UI

Tailwind UI

Mantine

Unstyled

The component also comes with an unstyled version. It's ideal for doing heavy customizations and minimizing bundle size.