Introducing PrimeReact v11-alpha 🎉Discover Now

ToggleSwitch

ToggleSwitch is used to select a boolean value.

preview

Installation#

npx shadcn@latest add https://v11.primereact.org/r/toggleswitch.json

Usage#

import { ToggleSwitch } from '@/components/ui/toggleswitch';
<ToggleSwitch />

Examples#

Basic#

basic-demo

Controlled#

A controlled ToggleSwitch requires managing the checked state with a state variable and handling the change event manually. This allows for complete control over the ToggleSwitch's behavior.

controlled-demo

Uncontrolled#

For an uncontrolled ToggleSwitch component, defaultChecked is used to set the initial state, and the component manages its own state internally.

uncontrolled-demo

Template#

ToggleSwitch also allows displaying custom content inside itself.

template-demo

Invalid#

Invalid state is displayed using the invalid prop to indicate a failed validation. You can use this style when integrating with form validation libraries.

invalid-demo

Disabled#

When disabled is present, the element cannot be edited and focused.

disabled-demo

Accessibility#

Screen Reader#

ToggleSwitch component uses a hidden native checkbox element with switch role internally that is only visible to screen readers. Value to describe the component can either be provided via label tag combined with id prop or using aria-labelledby, aria-label props.

<label htmlFor="switch1">Remember Me</label>
<ToggleSwitch inputId="switch1" />
 
<span id="switch2">Remember Me</span>
<ToggleSwitch aria-labelledby="switch2" />
 
<ToggleSwitch aria-label="Remember Me" />

Keyboard Support#

KeyFunction
tabMoves focus to the toggle switch.
spaceToggles the checked state.