Switch

An on/off toggle for settings that take effect immediately. The track glows in the accent color when the switch is on.

import { Switch } from 'jarvis-react-ui';

Uncontrolled

Without checked the switch keeps its own state. Set the initial state with defaultChecked.

import { Switch } from 'jarvis-react-ui';

export default function Uncontrolled() {
    return (
        <>
            <Switch label="Scanlines" />
            <Switch label="Grid" defaultChecked />
        </>
    );
}

Controlled

Pass checked and update it in onCheckedChange, which receives the new state.

import { useState } from 'react';
import { Switch } from 'jarvis-react-ui';

export default function Controlled() {
    const [sound, setSound] = useState(true);

    return (
        <div className="flex flex-col items-start gap-2">
            <Switch label="Sound" checked={sound} onCheckedChange={setSound} />
            <span className="text-[10px] text-text-muted">Audio {sound ? 'online' : 'muted'}</span>
        </div>
    );
}

Note: onClick

onClick runs before the toggle. Call event.preventDefault() in it to veto the change.

Sizes

import { Switch } from 'jarvis-react-ui';

export default function Sizes() {
    return (
        <>
            <Switch size="sm" label="Compact" defaultChecked />
            <Switch size="md" label="Default" defaultChecked />
        </>
    );
}

Disabled

import { Switch } from 'jarvis-react-ui';

export default function Disabled() {
    return (
        <>
            <Switch label="Autopilot" disabled />
            <Switch label="Telemetry" defaultChecked disabled />
        </>
    );
}

Sound

Hovering plays hover_button and toggling plays click through the nearest SfxProvider. See Sound effects.

Accessibility

  • Renders a native <button type="button"> with role="switch" and aria-checked, so Space and Enter toggle it.
  • The label is rendered inside the button and becomes its accessible name. Without a label, pass aria-label.
  • The track graphic is aria-hidden.

API

Prop Type Default Description
checked boolean Controlled on/off state. Leave undefined to use defaultChecked.
className string Additional class names for the root <button role="switch"> (wraps track and label).
defaultChecked boolean false Initial state when uncontrolled.
label ReactNode Visible label next to the track; also the accessible name.
onCheckedChange ((checked: boolean) => void) Called with the new state when the user toggles the switch.
size 'sm' | 'md' 'md' Track size.

Also accepts inherited props from ButtonHTMLAttributes (10), HTMLAttributes (53), AriaAttributes (53), DOMAttributes (168), RefAttributes (1), Attributes (1).