dear-digital / linter

3 stars 14 forks source link

💡 [REQUEST] - Efficient Text Copying with Clipboard API in React #43

Open kmalap05 opened 1 year ago

kmalap05 commented 1 year ago

Is there an existing issue for this?

Reference Issues

23

Description

Avoid Manipulating DOM Directly: Instead of creating and appending a temporary text area to the DOM for copying to the clipboard, we can use the Clipboard API, which is cleaner and more modern.

Basic Example

Previous Code:-

  const handleCopyToClipboard = (textToCopy) => {
    if (!error) {
      const tempTextArea = document.createElement("textarea");
      tempTextArea.value = textToCopy;
      document.body.appendChild(tempTextArea);
      tempTextArea.select();
      document.execCommand("copy");
      document.body.removeChild(tempTextArea);

      // Update the copy button state
      setIsCopied(true);
    } else {
      // Display the error (you can adjust the UI as needed)
      setIsCopied(false);
      alert(`Error: ${error}`);
    }
  };

Updated Code (More Optimized)

  const handleCopyToClipboard = (textToCopy) => {
    if (!error) {
      navigator.clipboard
        .writeText(textToCopy)
        .then(() => {
          // Update the copy button state
          setIsCopied(true);
        })
        .catch((err) => {
          // Handle clipboard write error
          console.error("Copy to clipboard failed:", err);
          setIsCopied(false);
        });
    } else {
      // Display the error (you can adjust the UI as needed)
      setIsCopied(false);
      alert(`Error: ${error}`);
    }
  };

Have you given as much information as possible about the feature?