implement
Switch

Switch

An on/off control that takes effect the moment it is flipped.

import { Div, Label } from "@implementjs/core";
import { Switch } from "@/lib/components/ui/switch";

export default function SwitchDemo() {
	return Div(
		{ class: "flex flex-col gap-4" },
		Div(
			{ class: "flex items-center gap-2" },
			Switch({ id: "airplane" }),
			Label({ for: "airplane", class: "text-sm leading-none font-medium" }, "Airplane mode"),
		),
		Div(
			{ class: "flex items-center gap-2" },
			Switch({ id: "marketing", checked: true }),
			Label({ for: "marketing", class: "text-sm leading-none font-medium" }, "Marketing emails"),
		),
		Div(
			{ class: "flex items-center gap-2" },
			Switch({ id: "disabled-switch", checked: true, disabled: true }),
			Label(
				{
					for: "disabled-switch",
					class:
						"text-sm leading-none font-medium peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
				},
				"Disabled",
			),
		),
	);
}

Installation

npx jsrepo add @implementjs/ui/switch

Nothing else comes with it — this one stands alone on @implementjs/core and @implementjs/primitives.

Usage

A switch is for a setting that applies immediately. When the change only lands on submit, use a checkbox.

The root renders a SwitchThumb for you unless you pass children — the thumb is exported for when you want a different one.

import { signal } from "@implementjs/core";
import { Switch } from "@/lib/components/ui/switch";

const airplaneMode = signal(false);

Switch({ id: "airplane", checked: airplaneMode });

With a label

Div(
	{ class: "flex items-center gap-2" },
	Switch({ id: "airplane" }),
	Label({ for: "airplane", class: "text-sm font-medium" }, "Airplane mode"),
);

API Reference

Every prop the styling does not consume is forwarded to the Switch primitive, so the tables below are the whole surface — the behavior props and the styling ones together.

Switch

A toggle that is on or off. Sets role="switch" and aria-checked. Give it a track and a thumb; it handles the state. Renders a SwitchThumb for you unless you pass children of your own. Renders a Button; extra props are forwarded onto it.

PropTypeDefaultDescription
checkedSignal<boolean> | booleanfalseThe checked state. Pass a signal to control it from outside; a boolean seeds uncontrolled state.
namestringIf set, a hidden checkbox is rendered so the value submits with a form.
valuestring"on"The value submitted while checked. Only used when name is set.
requiredbooleanfalseMarks the hidden input as required. Sets aria-required on the button.
Data attributeValue
[data-switch-root]Present
[data-state]"checked" | "unchecked"

SwitchThumb

The knob. Put it inside the switch and slide it with data-state. Styled as a circle that slides across when the switch turns on. Renders a Span; extra props are forwarded onto it.

Data attributeValue
[data-switch-thumb]Present
[data-state]"checked" | "unchecked"