JAVASCRIPT

Copy Text to Clipboard with a React Hook

A custom React hook to simplify copying text to the user's clipboard, providing feedback on success or failure of the operation.

import { useState, useCallback } from 'react';

function useCopyToClipboard() {
  const [copiedText, setCopiedText] = useState(null);

  const copy = useCallback(async (text) => {
    if (!navigator?.clipboard) {
      console.warn('Clipboard not supported');
      return false;
    }

    try {
      await navigator.clipboard.writeText(text);
      setCopiedText(text);
      return true;
    } catch (error) {
      console.error('Failed to copy: ', error);
      setCopiedText(null);
      return false;
    }
  }, []);

  return [copiedText, copy];
}

// Example Usage:
// function CopyTextComponent() {
//   const [copiedText, copy] = useCopyToClipboard();
//   const textToCopy = "Hello from React Hook!";
//
//   return (
//     <div>
//       <p>Text to copy: "{textToCopy}"</p>
//       <button onClick={() => copy(textToCopy)}>
//         {copiedText === textToCopy ? 'Copied!' : 'Copy to Clipboard'}
//       </button>
//       {copiedText && <p>You copied: {copiedText}</p>}
//     </div>
//   );
// }
How it works: The `useCopyToClipboard` hook exposes a `copy` function to programmatically copy text and a `copiedText` state variable to track the last successfully copied content. It leverages the modern `navigator.clipboard.writeText` API, handling potential browser incompatibilities or errors, and uses `useCallback` to memoize the `copy` function, preventing unnecessary re-creations.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs