Skip to content
Primitives

Switch

Radix switch with a Motion-driven thumb that springs between states.

Motionthumb x on spring.snappy

Install

Install Kineto and follow the theme setup once in your app.

bash
npm install kineto
tsx
import { Switch } from "kineto/switch";

Preview

tsx
"use client";

import * as React from "react";
import * as SwitchPrimitive from "@radix-ui/react-switch";
import { motion } from "motion/react";

import { cn } from "@/lib/cn";
import { spring } from "@/lib/motion-presets";

function useControllableState<T>({
  prop,
  defaultProp,
  onChange,
}: {
  prop: T | undefined;
  defaultProp: T;
  onChange?: (value: T) => void;
}): [T, (next: T) => void] {
  const [uncontrolled, setUncontrolled] = React.useState(defaultProp);
  const isControlled = prop !== undefined;
  const value = isControlled ? (prop as T) : uncontrolled;
  const setValue = React.useCallback(
    (next: T) => {
      if (!isControlled) setUncontrolled(next);
      onChange?.(next);
    },
    [isControlled, onChange]
  );
  return [value, setValue];
}

const Switch = React.forwardRef<
  React.ElementRef<typeof SwitchPrimitive.Root>,
  React.ComponentPropsWithoutRef<typeof SwitchPrimitive.Root>
>(({ className, checked, defaultChecked, onCheckedChange, ...props }, ref) => {
  const [isChecked, setIsChecked] = useControllableState({
    prop: checked,
    defaultProp: defaultChecked ?? false,
    onChange: onCheckedChange,
  });

  return (
    <SwitchPrimitive.Root
      ref={ref}
      checked={isChecked}
      onCheckedChange={setIsChecked}
      className={cn(
        "peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
        className
      )}
      {...props}
    >
      <SwitchPrimitive.Thumb asChild>
        <motion.span
          className="pointer-events-none block size-5 rounded-full bg-background shadow-soft"
          animate={{ x: isChecked ? 20 : 0 }}
          transition={spring.snappy}
        />
      </SwitchPrimitive.Thumb>
    </SwitchPrimitive.Root>
  );
});
Switch.displayName = "Switch";

export { Switch };

src/components/ui/switch.tsx

Props

PropTypeDefaultDescription
checked / defaultCheckedboolean—Controlled or uncontrolled state.
onCheckedChange(checked: boolean) => void—Fires on toggle.