JAVASCRIPT

Copy Text to Clipboard Easily with useCopyToClipboard

Implement a React hook, useCopyToClipboard, to programmatically copy any given text to the user's clipboard, providing a success/error state.

import { useState, useCallback } from 'react';

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

  const copy = useCallback(async (text) => {
    if (typeof text !== 'string' && typeof text !== 'number') {
      setError(new Error('Input must be a string or number.'));
      return false;
    }

    try {
      await navigator.clipboard.writeText(String(text));
      setCopiedText(String(text));
      setError(null);
      return true;
    } catch (err) {
      setError(err);
      setCopiedText(null);
      return false;
    }
  }, []);

  return [copiedText, copy, error];
}

export default useCopyToClipboard;
How it works: The useCopyToClipboard hook provides a simple interface to copy text to the user's system clipboard using the navigator.clipboard.writeText API. It returns the copiedText value (the text that was successfully copied), a copy function to trigger the action, and any potential error. This allows components to easily implement copy functionality, like 'copy to clipboard' buttons, and provide immediate user feedback on the operation's success or failure.

Need help integrating this into your project?

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

Hire DigitalCodeLabs