Forms
Switch
An immediate on or off choice, ready for a keyboard.
FOUNDATION / FORMS
Switch
You can change your mind anytime.
Interactive preview. Real components.View docs
Use it in your project
Install oscl-ui from npm and import oscl-ui/styles.css once. See installation.
switch-example.tsx
import { Switch } from "oscl-ui";
<Switch label="Enable notifications" defaultChecked />Accessibility
Keep visible labels and keyboard focus. Supply an accessible name to icon-only actions. Try this preview with Tab, Enter, Space, and Escape where appropriate.
The source, in full
This is the actual source from the isolated OSCL package used by this website. Native props and TypeScript declarations are included in the npm package.
switch.tsx
"use client";
import { forwardRef, useId } from "react";
import type { InputHTMLAttributes, ReactNode } from "react";
export interface SwitchProps extends Omit<InputHTMLAttributes<HTMLInputElement>, "type" | "role"> {
label: ReactNode;
description?: string;
}
export const Switch = forwardRef<HTMLInputElement, SwitchProps>(function Switch(
{ label, description, id, className = "", "aria-describedby": describedBy, ...props }, ref,
) {
const generatedId = useId();
const fieldId = id || generatedId;
return <div className={`oscl-choice oscl-switch-row ${className}`}>
<input {...props} ref={ref} type="checkbox" role="switch" id={fieldId} className="oscl-switch"
aria-describedby={[describedBy, description && `${fieldId}-description`].filter(Boolean).join(" ") || undefined} />
<div><label className="oscl-label" htmlFor={fieldId}>{label}</label>
{description && <p className="oscl-description" id={`${fieldId}-description`}>{description}</p>}</div>
</div>;
});