Copy to Clipboard

A hook that wraps navigator.clipboard and enhances it. You can also provide timeout to show small animation after copy button clicked.

copy to clipboard demo

use-clipboard.tsx

"use client";

import { useState } from "react";

interface UseCopyToClipboardProps {
  timeout?: number;
}

export function useCopyToClipboard({
  timeout = 2000,
}: UseCopyToClipboardProps) {
  const [isCopied, setIsCopied] = useState<boolean>(false);

  const copyToClipboard = (value: string) => {
    if (typeof window === "undefined" || !navigator.clipboard?.writeText) {
      return;
    }

    if (!value) {
      return;
    }

    navigator.clipboard.writeText(value).then(() => {
      setIsCopied(true);

      setTimeout(() => {
        setIsCopied(false);
      }, timeout);
    });
  };

  return { isCopied, copyToClipboard };
}

Usage

export default function MessageItem() {
  const { isCopied, copyToClipboard } = useCopyToClipboard({ timeout: 2000 });

  return (
    <Button
      onClick={copyToClipboard("some text")}
    >
      {isCopied ? <Icons.Check className="text-success" /> : <Icons.Copy />}
    </Button>;
  );
}

Loved this post?

Comments

Interested in
working
with me?