Copy Button

AI & Chat

Click-to-copy text button with feedback.

Preview

Click to copy!

Usage

example.jsx
import { CopyButton } from "@/components/ui/copy-button";

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

Source Code

Copy this file into components/ui/copy-button.jsx in your project.

copy-button.jsx
"use client";

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

const CopyButton = forwardRef(({ className, text, onCopy, ...props }, ref) => {
  const [copied, setCopied] = useState(false);
  const copy = async () => {
    await navigator.clipboard.writeText(text);
    setCopied(true);
    onCopy?.(text);
    setTimeout(() => setCopied(false), 2000);
  };
  return (
    <button ref={ref} onClick={copy} className={cn("inline-flex h-8 items-center gap-1.5 rounded-md border px-2.5 text-xs font-medium transition-colors hover:bg-accent", className)} {...props}>
      {copied ? (
        <><svg className="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" /></svg>Copied</>
      ) : (
        <><svg className="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><rect x="9" y="9" width="13" height="13" rx="2" ry="2" strokeWidth={2} /><path strokeWidth={2} d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1" /></svg>Copy</>
      )}
    </button>
  );
});
CopyButton.displayName = "CopyButton";

export { CopyButton };

Quick Install

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

npm install clsx tailwind-merge