Add correct fallback for copy to Clipboard API in React app

Viewed 12

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?

0 Answers
Related