Switch

Switches empower users to take control and activate or deactivate specific settings with a simple click.

UsageCodeAccessibility
Switch text
<sl-switch size="md" checked>Switch text</sl-switch>

When to use

A switch component is best used when:

Binary Settings

When you have straightforward on/off options that users should be able to control effortlessly, switches are the ideal choice. They offer a simple and intuitive way to switch between two states.

Instant Feedback

Ensure users receive immediate, clear visual feedback regarding the status of a setting. Changes are instantly visible when a switch is toggled.

When not to use

Contextual UI Elements

Avoid using switches when managing contextual UI elements such as expanding/collapsing a drawer, showing/hiding a menu, or toggling interface features on or off. In these cases, toggle buttons offer a more straightforward and efficient solution, maintaining clarity and usability in interface design.

Anatomy

ItemNameDescriptionOptional
1HandleTransforms between on and off states as the user navigates to its setting.no
2On/off iconA visual cue is placed within the track to indicate that the switch is 'on' or 'off'.yes
3Slider trackThe background area serves as the pathway for the switch handle's movement.no
4LabelDescribes the purpose and context of the switch component.yes
5Help text/hintThe help text offers guidance, it explains to the user what happens when turning the option on or off.yes

Figma Options

With these options, you can tweak the appearance of the switch in Figma. They are available in the Design Panel so you can compose the switch to exactly fit the user experience need for the use case you are working on.

Switch

ItemOptionsDescription
Sizessm md lgThe switch come in three sizes: small, medium (default) and large.
Orientationleft rightThe switch has 2 different lay-out possibilities relating to the positions of the label and switch relative to each other.
DisabledbooleanTo indicate if the switch is enabled or disabled
LabelvalueTo insert the text of the label
StatusbooleanTo indicate if the switch is checked or unchecked
Statedefault hover active disabledTo indicate the state of the switch
IconbooleanTo show an icon in the handle of the switch
Focus ringbooleanTo show the focus state of the switch

Hint

ItemOptionsDescription
HintbooleanTo show a hint
Statedefault invalid disableTo indicate the state of the hint
Sizesm md lgThe hint come in three sizes: small, medium (default) and large.
TextvalueTo insert the text of the hint
Default checkedReverse unchecked
<sl-switch size="md" checked>Default checked</sl-switch>
<sl-switch size="md" reverse>Reverse unchecked</sl-switch>

API

The switch component has a range of properties to define the experience in different use cases. It is commonly used to enable and disable different options.

Properties

NameAttributeTypeDefaultDescription
checkedcheckedboolean | undefinedWhether the switch is on or off.
customValiditycustom-validitystring | undefinedThe error message to display when the control is invalid.
dirty-booleanfalseA control is dirty if the user has changed the value in the UI.
disableddisabledboolean | undefinedWhether the switch is disabled; when set no interaction is possible.
form-HTMLFormElement | nullThe form associated with the control.
formValue-unknownThe value used when submitting the form.
iconOfficon-offstring | undefinedCustom icon in "off" state.
iconOnicon-onstring | undefinedCustom icon in "on" state.
input-HTMLInputElementThe input element in the light DOM.
labels-`NodeListOf<HTMLLabelElement>` | nullThe labels associated with the control.
namenamestring | undefinedThe name of the form control.
nativeFormValue-FormValueReturns the form value as used in a native `<form>`. This is always a string, File, FormData or null.
reversereverseboolean | undefinedWhether the toggle should be shown *after* the text.
showValid-booleanfalseOptional property to indicate the valid state should be shown.
showValidityshow-validity'valid' | 'invalid' | undefinedWhether to show the validity state.
sizesize'sm' | 'md' | 'lg''md'The size of the switch.
touched-booleanfalseA control is marked touched once the user has triggered a blur event on it.
valid-booleanReturns whether the form control is valid or not.
validationMessage-stringString representing a localized (by the browser) message that describes the validation
constraints that the control does not satisfy (if any). The string is empty if the control
is not a candidate for constraint validation, or it satisfies its constraints.

For true localization, see `getLocalizedValidationMessage()` instead.
validity-ValidityStateReturns the validity state the control is in.
validityState-'valid' | 'invalid' | 'pending'Returns the current validity state.
valuevalueunknown | undefinedThe value of the switch when the switch is checked.
See the formValue property for easy access.

Methods

NameParametersReturnDescription
focusvoid
blurvoid
setAttributesTargettarget: HTMLElementvoid
reportValiditybooleanReturns whether the control is valid. If the control is invalid, calling this will
also cause an `invalid` event to be dispatched. After calling this, the control
will also report the validity to the user.
resetvalue: unknownvoid
getLocalizedValidationMessagestringThis returns a localized validation message. It does not support all `ValidityState` properties,
since some require more context than we have here. If you need to support more, you can override
this method in your own form control.
setCustomValiditymessage: string | Promise<string>voidSets a custom validation message for the form control. If the message
is not an empty string, that will make the control invalid. By setting it to
an empty string again, you can make the control valid again.

Events

NameEvent typeDescription
sl-blurSlBlurEventEmits when the component loses focus.
sl-changeSlChangeEvent<T | null>Emits when the checked state changes.
sl-focusSlFocusEventEmits when the component receives focus.
sl-form-controlSlFormControlEventEmits when the form control is added to the DOM.
sl-update-stateSlUpdateStateEventEmits when the UI state (dirty, pristine, touched or untouched) of the form control changes.
sl-update-validitySlUpdateValidityEventEmits when the validity of the form control changes.
sl-validateSlValidateEventEmits when the form control can be validated.

Slots

NameDescription
defaultText label of the switch. Technically there are no limits what can be put here; text, images, icons etc.
inputThe slot for the input element

When designed with accessibility in mind, switches can be useful for users with disabilities, as they offer a clear and easily distinguishable way to change settings.

Keyboard interactions

Navigating and using switch components with a keyboard is a seamless experience, ensuring accessibility for all users. Here's a breakdown of the keyboard interactions:

CommandDescription
TabPressing the 'Tab' key allows users to move focus to the switch. Once focused, they can activate the switch using the 'Space' key.
Space/EnterWhen the switch is in focus, hitting the 'Enter' or 'Space' key toggles it between the 'on' and 'off' states. This intuitive action ensures that users can easily control the switch without the need for a mouse.

These keyboard interactions make switch components not only accessible but also user-friendly, catering to a diverse range of user needs and preferences.

WAI-ARIA

When it comes to ensuring accessibility for switch components, we turn to the power of WAI-ARIA (Web Accessibility Initiative - Accessible Rich Internet Applications). Here's how WAI-ARIA contributes:

AttributeValueDescriptionUser suppliedSpecifies whether the attribute is always set in the component (no) or it needs to be provided by the developer (yes)
aria-checked'true','false'The state of the switch.no
role'switch'Declare our custom component as a switch.no
aria-labelstringCan be added when the switch doesn't have a label text or label component connected with.yes
aria-describedbystringUsed to describe (link with) hint (helper text) and/or error message.no
aria-disabledbooleanAnnounces the switch component as disabled with a screen reader. See [Note 1] below.yes
aria-labelledbystringWhen multiple switches are used to connect with single header that describes those switches.yes

Notes:

  1. The aria-disabled should not be used as a one-for-one replacement for the disabled attribute because they have different functionalities:
  • disabled dims the switch visually, takes it out of the tab-focus sequence, prevents actions (click, enter) on it and announces it as 'dimmed' or 'disabled' in a screen reader.
  • aria-disabled only does the latter. You will need to disable the functionality yourself. This might be useful for scenarios where you don't want to take the switch out of the navigation flow.

When disabled is added to a switch component there is no need to also add aria-disabled. Everything aria-disabled does, disabled does as well. You can read more on the difference and in which scenarios which option might be preferable on the MDN page about aria-disabled.

Interactive example