Component
Switch
Native switch styled to the DevSnips select/input visual language with controlled and uncontrolled modes.
- Component
- React
- TSX
- Tailwind CSS
- MIT
Preview
Live component
9:41 100%
devsnips.dev/library/react/components/switches/switch/ fluid · no fixed width 100%
Install
Add to your project
npx devsnips add React/Components/Switches/switch React/Components/Switches/switch import type { ChangeEvent, ReactNode } from "react";
import { useId, useState } from "react";
function cx(...parts: Array<string | false | null | undefined>): string {
return parts.filter(Boolean).join(" ");
}
export interface SwitchProps {
/** Accessible label when rendered; omit and set aria-label for a bare control. */
label?: ReactNode;
checked?: boolean;
defaultChecked?: boolean;
onChange?: (checked: boolean, event: ChangeEvent<HTMLInputElement>) => void;
disabled?: boolean;
required?: boolean;
invalid?: boolean;
name?: string;
value?: string | number | readonly string[];
id?: string;
"aria-label"?: string;
"aria-labelledby"?: string;
"aria-describedby"?: string;
className?: string;
children?: ReactNode;
}
/**
* Native switch styled to the DevSnips select/input visual language. A real
* `<input type="checkbox" role="switch">` carries all native behavior; the
* thumb position tracks the tracked `isChecked` state. Controlled
* (`checked`/`onChange`) and uncontrolled (`defaultChecked`) modes are both
* supported.
*/
export function Switch({
label,
checked,
defaultChecked,
onChange,
disabled,
required,
invalid,
name,
value,
id,
"aria-label": ariaLabel,
"aria-labelledby": ariaLabelledby,
"aria-describedby": ariaDescribedby,
className,
children,
}: SwitchProps) {
const generatedId = useId();
const inputId = id ?? `switch-${generatedId}`;
const isControlled = checked !== undefined;
const [internal, setInternal] = useState<boolean>(defaultChecked ?? false);
const isChecked = isControlled ? checked : internal;
function handleChange(event: ChangeEvent<HTMLInputElement>) {
const next = event.target.checked;
if (!isControlled) setInternal(next);
onChange?.(next, event);
}
const control = (
<span className={cx("relative inline-flex h-[14px] w-[24px] shrink-0 items-center", disabled && "opacity-50")}>
<input
id={inputId}
type="checkbox"
role="switch"
aria-checked={isChecked}
className={cx(
"absolute inset-0 h-full w-full cursor-pointer appearance-none rounded-full border transition-colors duration-150 ease-out hover:border-[var(--ds-color-border-strong)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--ds-color-focus-ring)] disabled:cursor-not-allowed motion-reduce:transition-none",
invalid
? (isChecked
? "border-[var(--ds-color-destructive)] bg-[var(--ds-color-destructive)]"
: "border-[var(--ds-color-destructive)]")
: isChecked
? "border-[var(--ds-color-primary)] bg-[var(--ds-color-primary)]"
: "border-[var(--ds-color-border)] bg-[var(--ds-color-input)]",
className,
)}
checked={isControlled ? isChecked : undefined}
defaultChecked={isControlled ? undefined : defaultChecked}
disabled={disabled}
required={required}
aria-invalid={invalid ? true : undefined}
aria-label={ariaLabel}
aria-labelledby={ariaLabelledby}
aria-describedby={ariaDescribedby}
name={name}
value={value}
onChange={handleChange}
/>
<span
aria-hidden="true"
className={cx(
"pointer-events-none absolute left-[2px] top-[2px] size-[10px] rounded-full transition-[transform,background-color] duration-150 ease-out motion-reduce:transition-none",
isChecked ? "translate-x-[10px]" : "translate-x-0",
invalid && isChecked
? "bg-[var(--ds-color-destructive-foreground)]"
: isChecked
? "bg-[var(--ds-color-primary-foreground)]"
: "bg-[var(--ds-color-muted-foreground)]",
)}
/>
</span>
);
if (!label && !children) {
return control;
}
const labelContent = children ?? label;
return (
<label
htmlFor={inputId}
className={cx(
"inline-flex items-center gap-2.5 text-sm leading-5 text-[var(--ds-color-foreground)]",
disabled ? "cursor-not-allowed" : "cursor-pointer",
)}
>
{control}
{labelContent ? <span className="select-none">{labelContent}</span> : null}
</label>
);
}
export default Switch; /* DevSnips React — JavaScript parity build.
* Same API, behavior, and classes as code.tsx; TypeScript types removed.
* Regenerated from code.tsx — edit code.tsx and re-run the generator.
*/
import { useId, useState } from "react";
function cx(...parts) {
return parts.filter(Boolean).join(" ");
}
export function Switch({
label,
checked,
defaultChecked,
onChange,
disabled,
required,
invalid,
name,
value,
id,
"aria-label": ariaLabel,
"aria-labelledby": ariaLabelledby,
"aria-describedby": ariaDescribedby,
className,
children
}) {
const generatedId = useId();
const inputId = id ?? `switch-${generatedId}`;
const isControlled = checked !== undefined;
const [internal, setInternal] = useState(defaultChecked ?? false);
const isChecked = isControlled ? checked : internal;
function handleChange(event) {
const next = event.target.checked;
if (!isControlled) setInternal(next);
onChange?.(next, event);
}
const control = <span className={cx("relative inline-flex h-[14px] w-[24px] shrink-0 items-center", disabled && "opacity-50")}>
<input
id={inputId}
type="checkbox"
role="switch"
aria-checked={isChecked}
className={cx(
"absolute inset-0 h-full w-full cursor-pointer appearance-none rounded-full border transition-colors duration-150 ease-out hover:border-[var(--ds-color-border-strong)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--ds-color-focus-ring)] disabled:cursor-not-allowed motion-reduce:transition-none",
invalid ? isChecked ? "border-[var(--ds-color-destructive)] bg-[var(--ds-color-destructive)]" : "border-[var(--ds-color-destructive)]" : isChecked ? "border-[var(--ds-color-primary)] bg-[var(--ds-color-primary)]" : "border-[var(--ds-color-border)] bg-[var(--ds-color-input)]",
className
)}
checked={isControlled ? isChecked : undefined}
defaultChecked={isControlled ? undefined : defaultChecked}
disabled={disabled}
required={required}
aria-invalid={invalid ? true : undefined}
aria-label={ariaLabel}
aria-labelledby={ariaLabelledby}
aria-describedby={ariaDescribedby}
name={name}
value={value}
onChange={handleChange}
/>
<span
aria-hidden="true"
className={cx(
"pointer-events-none absolute left-[2px] top-[2px] size-[10px] rounded-full transition-[transform,background-color] duration-150 ease-out motion-reduce:transition-none",
isChecked ? "translate-x-[10px]" : "translate-x-0",
invalid && isChecked ? "bg-[var(--ds-color-destructive-foreground)]" : isChecked ? "bg-[var(--ds-color-primary-foreground)]" : "bg-[var(--ds-color-muted-foreground)]"
)}
/>
</span>;
if (!label && !children) {
return control;
}
const labelContent = children ?? label;
return <label
htmlFor={inputId}
className={cx(
"inline-flex items-center gap-2.5 text-sm leading-5 text-[var(--ds-color-foreground)]",
disabled ? "cursor-not-allowed" : "cursor-pointer"
)}
>
{control}
{labelContent ? <span className="select-none">{labelContent}</span> : null}
</label>;
}
export default Switch; # Switch
Native switch styled to the DevSnips select/input visual language with controlled and uncontrolled modes.
## Usage
```tsx
<Switch label="Email notifications" defaultChecked />
```
## JavaScript
A `code.jsx` build is provided for projects that ship plain JSX. It exposes the same API and behavior as `code.tsx` — only the TypeScript types are removed.
```jsx
<Switch label="Email notifications" defaultChecked />
```
## Props
| Name | Type | Default | Description |
|---|---|---:|---|
| `label` | `ReactNode` | — | Visible label (omit for an icon-only / aria-label control). |
| `checked` / `defaultChecked` | `boolean` | `false` | Controlled / uncontrolled checked state. |
| `onChange` | `(checked, event) => void` | — | Change callback. |
| `disabled` | `boolean` | — | Disables the control. |
| `required` | `boolean` | — | Marks the field required (renders `*`). |
| `invalid` | `boolean` | — | Sets `aria-invalid` + destructive styling. |
| `name` / `value` | `string` | — | Native form name/value. |
| `id` | `string` | generated | Input id (also the label `htmlFor`). |
| `aria-label` / `aria-labelledby` / `aria-describedby` | `string` | — | Override association. |
## States
A native `<input type="checkbox" role="switch">` styled with Tailwind + the `--ds-*` semantic tokens. The thumb position tracks the tracked `isChecked` state; controlled (`checked`/`onChange`) and uncontrolled (`defaultChecked`) modes are both supported. A switch is an immediate binary setting — it takes effect the moment it toggles.
## Accessibility
Real `<input type="checkbox" role="switch">` element with an explicit `aria-checked` — full native keyboard (Space toggles), `aria-invalid` for errors, `aria-describedby` for associated text, visible `focus-visible` ring from `--ds-color-focus-ring`. When a label is provided it is wrapped in a `<label htmlFor>` so the text is a click target. When no label is rendered, pass `aria-label` or `aria-labelledby`.
## Styling
Built with React, Tailwind CSS, and DevSnips design tokens. The component consumes the `--ds-*` semantic tokens via arbitrary values (for example `bg-[var(--ds-color-primary)]`). Define the tokens once in your theme — no component-specific CSS file is required.
## Design Tokens
See [React/DESIGN_TOKENS.md](../../../DESIGN_TOKENS.md) for the authoritative token specification. This switch uses the semantic color, radius, spacing, and motion tokens.
## Notes
This is the reference implementation for the Switches family — it establishes the shared 24×14px track, 10px thumb, full radius, border, focus ring, on/off/disabled/error states, and dark-mode behavior that every other switch extends. 127 lines UTF-8 · LF · Spaces: 2
Continue browsing