Skip to content
shadcn.io

shadcn.io is not affiliated with official shadcn/ui

Switch examples · Icons

Theme Toggle with Icons Switch for React

A switch between a sun and a moon icon for light and dark mode.

Framework
UI library

A Switch with a sun before it and a moon after it, the familiar shape of a light and dark toggle. The icons are decoration; the switch keeps its own state, so connect it to your theme code to change the page.

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

Do the sun and moon change when the switch toggles?

No. SunIcon is size-4, and MoonIcon adds text-muted-foreground; those classes stay as written. Both have aria-hidden, in a flex items-center gap-2 row.

What do screen readers call this switch?

The icons are hidden from screen readers, so the switch has aria-label (Dark mode). Keep a text name whenever the icons are the only cue.

How do I control this switch in React?

Nothing in this file sets the on state, so the switch starts off and keeps its own state. To control it, keep the on or off state in your own state and pass it back. To start it on, use the default prop. The prop is defaultChecked. Pass checked; onCheckedChange receives the new boolean.

How do I add a visible label to this switch?

Put the Switch in a horizontal Field next to a FieldLabel. Clicking the label toggles the switch, and screen readers read the label with it. Give the Switch an id and set the same value as htmlFor on the FieldLabel.

How do I make this switch smaller?

Set size="sm". The default size is default. For a different track or thumb, edit those classes in the Switch file in your ui folder.

Which keys toggle the switch?

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