Forms

Switch

Form switch for boolean states

Preview

size
label
required
error
disabled

Code

import css from "./Switch.module.css";
import { useState } from "react";

type Size = "xs" | "sm" | "md" | "lg";

interface ResponsiveSize {
  base: Size;
  mobile?: Size;
  tablet?: Size;
  desktop?: Size;
  wide?: Size;
}

interface SwitchProps {
  size: Size | ResponsiveSize;
  name?: string;
  label?: string;
  "aria-label"?: string;
  checked: boolean;
  required?: boolean;
  error?: boolean;
  disabled?: boolean;
  onChange: (checked: boolean) => void;
}

function getSizeClasses(size: Size | ResponsiveSize): string {
  if (typeof size === "string") {
    return css[size];
  }

  const classes = [css[`${size.base}_base`]];

  if (size.mobile) classes.push(css[`${size.mobile}_mobile`]);
  if (size.tablet) classes.push(css[`${size.tablet}_tablet`]);
  if (size.desktop) classes.push(css[`${size.desktop}_desktop`]);
  if (size.wide) classes.push(css[`${size.wide}_wide`]);

  return classes.join(" ");
}

export default function Switch({
  size,
  name,
  label,
  "aria-label": ariaLabel,
  checked,
  required,
  error,
  disabled,
  onChange,
}: SwitchProps) {
  const [interacted, setInteracted] = useState(false);

  const handleChange = (ev: React.ChangeEvent<HTMLInputElement>) => {
    setInteracted(true);
    onChange(ev.target.checked);
  };

  const toggle = () => {
    if (disabled) return;
    setInteracted(true);
    onChange(!checked);
  };

  const onKeyDown = (ev: React.KeyboardEvent) => {
    if (ev.key === "Enter") {
      ev.preventDefault();
      toggle();
    }
  };

  const Wrapper = label ? "label" : "span";

  return (
    <Wrapper
      className={`
        ${css.switch}
        ${getSizeClasses(size)}
        ${error ? css.error : ""}
        ${disabled ? css.disabled : ""}
      `}
    >
      <input
        type="checkbox"
        role="switch"
        name={name}
        checked={checked}
        required={required}
        disabled={disabled}
        aria-label={label ? undefined : ariaLabel}
        aria-invalid={error}
        onChange={handleChange}
        onKeyDown={onKeyDown}
      />
      <span className={`${css.switch_box} ${checked ? css.active : ""}`}>
        <span
          className={`${css.box_dot} ${interacted ? css.animated : ""}`}
        ></span>
      </span>
      {label && (
        <span className={css.switch_label}>
          {label}
          {required && <span aria-hidden="true">*</span>}
        </span>
      )}
    </Wrapper>
  );
}

Props

PropTypeRequiredDescription
size"xs" | "sm" | "md" | "lg" | ResponsiveSizerequiredSwitch size (track, dot and label). Fixed or responsive.
namestring—Field name when it lives in a form; without it, it is not submitted.
labelstring—Text next to the switch. Without a label, only the track remains.
aria-labelstring—Name of the control for screen readers. Required when there is no label; ignored when there is one.
requiredboolean—Marks the field as required (adds * to the label and the native required).
errorboolean—Visual error state (red border, aria-invalid).
disabledboolean—Disables the switch (not interactive, reduced opacity).
checkedbooleanrequiredOn state (controlled).
onChange(checked: boolean) => voidrequiredCallback with the new state on every change.