Introducing PrimeReact v11-alpha 🎉Discover Now

Switch

Switch is used to select a boolean value.

preview

Installation#

npx shadcn@latest add @primereact/ui/switch

Usage#

import { Switch } from '@/components/ui/switch';
<Switch />

Examples#

Basic#

basic-demo

Controlled#

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

controlled-demo

Uncontrolled#

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

uncontrolled-demo

Template#

Switch 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#

Switch 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>
<Switch inputId="switch1" />
 
<span id="switch2">Remember Me</span>
<Switch aria-labelledby="switch2" />
 
<Switch aria-label="Remember Me" />

Keyboard Support#

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