Skip to content
shadcn.io

shadcn.io is not affiliated with official shadcn/ui

Form examples · Advanced

Form with Switch for React

Three notification switches, email, push and desktop, each on a bordered row with its label and description.

Framework
UI library

On/off preferences read best as switches. Under a Notification Settings legend, each row is a bordered horizontal Field with a FieldContent for the label and description and the Switch on the other side. A Controller wires each switch into React Hook Form, and the schema is three booleans, so there is nothing to fail. Use it for notification settings, feature toggles or privacy controls.

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 each switch connected to the form?

The rows come from one notifications array mapped to a Controller each. Switch takes checked={field.value} and onCheckedChange={field.onChange}.

Which switches start on?

defaultValues sets emailNotifications and desktopNotifications to true and pushNotifications to false.

How is each row arranged?

Each row is Field orientation="horizontal" with rounded-lg border p-4: FieldContent with the FieldLabel and FieldDescription first, then the Switch. The rows sit in a FieldGroup inside a FieldSet whose FieldLegend is Notification Settings.

What do the three descriptions say?

Email Notifications: "Receive notifications via email." Push Notifications: "Receive push notifications on your device." Desktop Notifications: "Receive notifications on your desktop."

Does this form show a validation message?

No. Each value is z.boolean(), and on or off both pass, so the rows have no FieldError. Add a refine and a FieldError if one setting must be on.

What does Save Preferences log?

Save Preferences is a type="submit" button. form.handleSubmit(onSubmit) logs { desktopNotifications, emailNotifications, pushNotifications } to the console.