Skip to content
shadcn.io

shadcn.io is not affiliated with official shadcn/ui

Switch examples · Square

Square Switch with Text for React

A square switch with On and Off text that slides with its thumb.

Framework
UI library

A wide square Switch with its state written on the track: Off while the thumb sits at the start, On once it slides across. The words remove the guesswork for settings where on and off must be unmistakable, such as power or live mode.

Preview

Preview width

Installation

Sign in to get your install command
Free with an account. It carries your token, so the CLI installs everything in one go.

FAQ

How is the On and Off switch laid out?

A two-column grid with h-9 and grid-cols-[1fr_1fr] holds the Off and On words. The Switch is peer absolute inset-0 with h-[inherit] w-auto rounded-md, so it covers both columns, and its thumb is h-full w-1/2.

What moves the thumb and the words?

When the switch is on, the thumb moves with translate-x-full, over 300ms with a custom easing. The words are siblings after the switch, so peer- classes show On and hide Off when it is on, and rtl: classes slide the other way. The state classes use data-checked and data-unchecked.

Is there a text name for this switch?

The visible On and Off words describe the state, not the setting, so the demo passes aria-label (Labeled switch). Change it to the setting the switch controls.

How do I control this switch in React?

This file keeps the state itself, starting on, and passes it back to the Switch. Pass checked; onCheckedChange receives the new boolean.

Does this switch submit with a form?

Give it a name. When on, it submits its value, which defaults to on. When off, it submits nothing. With Base UI, uncheckedValue sets what it submits when off.

Which keys toggle the switch?

Tab moves focus to the switch. Space toggles it, and so does Enter.