Data Display
Forms
Navigation
Switch
A control that indicates whether a setting is on or off.
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
export default function Particle() {
return (
<Label>
<Switch />
Marketing emails
</Label>
);
}
Installation
pnpm dlx cnippet@latest add switch
Usage
import { Switch } from "@/components/ui/switch"<Switch />Examples
For accessible labelling and validation, prefer using the Field component to wrap checkboxes. See the related example: Switch field.
With Description
By enabling marketing emails, you agree to receive emails.
import * as React from "react";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
export default function Particle() {
const id = React.useId();
return (
<div className="flex items-start gap-2">
<Switch defaultChecked id={id} />
<div className="flex flex-col gap-1">
<Label htmlFor={id}>Marketing emails</Label>
<p className="text-muted-foreground text-xs">
By enabling marketing emails, you agree to receive emails.
</p>
</div>
</div>
);
}
Card Style
import * as React from "react";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
export default function Particle() {
const id = React.useId();
return (
<Label
className="flex items-center gap-6 rounded-lg border p-3 hover:bg-accent/50 has-data-checked:border-primary/48 has-data-checked:bg-accent/50"
htmlFor={id}
>
<div className="flex flex-col gap-1">
<p>Enable notifications</p>
<p className="text-muted-foreground text-xs">
You can enable or disable notifications at any time.
</p>
</div>
<Switch defaultChecked id={id} />
</Label>
);
}
Form Integration
"use client";
import * as React from "react";
import { Button } from "@/components/ui/button";
import { Field, FieldLabel } from "@/components/ui/field";
import { Form } from "@/components/ui/form";
import { Switch } from "@/components/ui/switch";
export default function Particle() {
const [loading, setLoading] = React.useState(false);
const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const formData = new FormData(e.currentTarget);
setLoading(true);
await new Promise((r) => setTimeout(r, 800));
setLoading(false);
console.log(formData.get("marketing"));
const enabled = formData.get("marketing");
alert(`Marketing emails: ${enabled}`);
};
return (
<Form className="w-auto" onSubmit={onSubmit}>
<Field name="marketing">
<FieldLabel>
<Switch defaultChecked disabled={loading} name="marketing" />
Enable marketing emails
</FieldLabel>
</Field>
<Button disabled={loading} type="submit">
Submit
</Button>
</Form>
);
}