Toggle

Form

Pressable toggle button with on/off states.

Preview

Usage

example.jsx
import { Toggle } from "@/components/ui/toggle";

export default function Example() {
  return <Toggle />;
}

Source Code

Copy this file into components/ui/toggle.jsx in your project.

toggle.jsx
"use client";

import { forwardRef } from "react";
import { cn } from "@/lib/utils";

const Toggle = forwardRef(
  ({ className, pressed, onPressedChange, variant = "default", size = "default", children, ...props }, ref) => {
    return (
      <button
        ref={ref}
        type="button"
        role="switch"
        aria-pressed={pressed}
        onClick={() => onPressedChange?.(!pressed)}
        className={cn(
          "inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors cursor-pointer",
          "hover:bg-muted hover:text-muted-foreground",
          "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
          "disabled:pointer-events-none disabled:opacity-50",
          pressed && "bg-accent text-accent-foreground",
          variant === "outline" && "border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground",
          size === "default" && "h-9 px-3",
          size === "sm" && "h-8 px-2",
          size === "lg" && "h-10 px-4",
          className
        )}
        {...props}
      >
        {children}
      </button>
    );
  }
);
Toggle.displayName = "Toggle";

export { Toggle };

Quick Install

Make sure you have the cn() utility set up. It requires clsx and tailwind-merge.

npm install clsx tailwind-merge