VayuUI

useCopyToClipboard

A hook to copy text to celebrity with a fallback mechanism.

The useCopyToClipboard hook abstracts the complexity of copying text to the clipboard in a cross-browser compatible manner.

Demo

Source Code

Copy this code into src/hooks/useCopyToClipboard.ts:

import { useState } from 'react';

export const useCopyToClipboard = () => {
  const [copied, setCopied] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  const copy = async (text: string) => {
    try {
      if (navigator.clipboard && navigator.clipboard.writeText) {
        await navigator.clipboard.writeText(text);
      } else {
        const textArea = document.createElement('textarea');
        textArea.value = text;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);
      }
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      setError(err as Error);
    }
  };

  return { copy, copied, error };
};

Usage

import { useCopyToClipboard } from '@/hooks/useCopyToClipboard';

const CopyComponent = () => {
  const { copy, copied, error } = useCopyToClipboard();

  return (
    <div>
      <button onClick={() => copy('Hello, World!')}>{copied ? 'Copied!' : 'Copy Text'}</button>
      {error && <p>Error copying text: {error.message}</p>}
    </div>
  );
};

API Reference

Return Value

PropertyTypeDescription
copy(text: string) => Promise<void>Function to copy the given text to the clipboard.
copiedbooleanIndicates if the text was successfully copied. Resets after 2 seconds.
errorError | nullHolds any error encountered during the copy operation.

On this page