Published on

🪝 How to copy to clipboard with custom hook

Custom Hook: useCopyToClipboard.ts

import { useState, useCallback } from 'react';

const useCopyToClipboard = () => {
  const [isCopied, setIsCopied] = useState<boolean>(false);

  const copyToClipboard = useCallback(async (text: string) => {
    try {
      await navigator.clipboard.writeText(text);
      setIsCopied(true);

      // Reset isCopied to false after 2 seconds
      setTimeout(() => setIsCopied(false), 2000);
    } catch (err) {
      console.error('Failed to copy: ', err);
      setIsCopied(false);
    }
  }, []);

  return { isCopied, copyToClipboard };
};

export default useCopyToClipboard;

How to Use the Custom Hook in a Component

import React from 'react';
import useCopyToClipboard from './useCopyToClipboard'; // Adjust the path as necessary

const CopyExample: React.FC = () => {
  const { isCopied, copyToClipboard } = useCopyToClipboard();

  const handleCopy = () => {
    copyToClipboard('This text has been copied to clipboard!');
  };

  return (
    <div>
      <button onClick={handleCopy}>
        Copy Text
      </button>
      {isCopied && <span style={{ color: 'green' }}>Copied!</span>}
    </div>
  );
};

export default CopyExample;