0

I am using React 17 and building a Copy to clipboard functionality:

I have some state:

const [isCopied, setIsCopied] = useState(false);

Then the functions:

  const copyTextToClipboard = async (text: string) => {
    if (navigator?.clipboard?.writeText) {
      await navigator.clipboard.writeText(text);
    }
    // What to do here since `document.execCommand('copy', true, text);` is deprecated??
  };

  const handleCopyClick = () => {
    copyTextToClipboard(copyText)
      .then(() => {
        setIsCopied(true);
        setTimeout(() => {
          setIsCopied(false);
        }, 1500);
      })
      .catch((err) => {
        console.log(err);
      });
  };

Then inside the jsx I have the text and the button:

  <p>{copyText}</p>
  <button type="button" onClick={handleCopyClick}>
    <span>{isCopied ? 'Copied!' : 'Copy'}</span>
  </button>

Can this code be optimised/refactored and be cleaner? And how to add the fallback for copy to Clipboard API when it's not supported, or is that not needed since all modern browsers support it?

meez
  • 3,783
  • 5
  • 37
  • 91
  • Does this answer your question? [What is the best way to implement a Copy to clipboard functionality in React](https://stackoverflow.com/questions/73662603/what-is-the-best-way-to-implement-a-copy-to-clipboard-functionality-in-react) – Reifocs Sep 14 '22 at 13:26

0 Answers0