Components
Text & Editing

Copy Button

A copy-to-clipboard button for React where the icon morphs into a check and the label rolls to Copied.

pnpm add motion
Plays on its own. Click to take over.

Install

Copies the source into components/ui/copy-button.tsx and installs what it needs.

$ pnpm dlx shadcn@latest add https://makeui.xyz/r/copy-button.json

Usage

app/page.tsx
import { CopyButton } from "@/components/ui/copy-button"

export default function Example() {
  return <CopyButton text="pnpm add motion" />
}

Source

Prefer to copy by hand? It's one file. Requires motion and the shadcn cn helper.

components/ui/copy-button.tsx
"use client"

import { useState } from "react"
import { AnimatePresence, motion } from "motion/react"
import { Check, Copy } from "lucide-react"
import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button"

type Props = {
  text?: string
  label?: string
  /** Controlled "copied" state. Leave out to let it manage itself. */
  copied?: boolean
  onCopy?: () => void
  className?: string
}

/** Copy button: the icon morphs to a check and the label rolls to "Copied". */
export function CopyButton({
  text = "pnpm dlx shadcn@latest add https://makeui.xyz/r/copy-button.json",
  label = "Copy",
  copied,
  onCopy,
  className,
}: Props) {
  const [internal, setInternal] = useState(false)
  const done = copied ?? internal

  async function copy() {
    try {
      await navigator.clipboard.writeText(text)
      setInternal(true)
      setTimeout(() => setInternal(false), 1600)
      onCopy?.()
    } catch {
      /* clipboard blocked */
    }
  }

  const swap = {
    initial: { opacity: 0, scale: 0.5, filter: "blur(4px)" },
    animate: { opacity: 1, scale: 1, filter: "blur(0px)" },
    exit: { opacity: 0, scale: 0.5, filter: "blur(4px)" },
    transition: { duration: 0.18 },
  }

  return (
    <button
      type="button"
      onClick={copy}
      className={cn(buttonVariants({ variant: "primary", size: "md" }), className)}
    >
      <span className="relative grid size-4 place-items-center">
        <AnimatePresence mode="popLayout" initial={false}>
          <motion.span key={done ? "c" : "i"} {...swap} className="absolute">
            {done ? (
              <Check className="size-4 text-emerald-400 dark:text-emerald-600" strokeWidth={3} />
            ) : (
              <Copy className="size-4" />
            )}
          </motion.span>
        </AnimatePresence>
      </span>
      <span className="relative inline-flex overflow-hidden">
        <AnimatePresence mode="popLayout" initial={false}>
          <motion.span key={done ? "c" : "i"} {...swap} className="inline-block">
            {done ? "Copied" : label}
          </motion.span>
        </AnimatePresence>
      </span>
    </button>
  )
}