Explain

In reactJS, how to copy text to clipboard?

Copying text to the clipboard in modern React applications can be done in a few different ways. Below are two common approaches:

1. Using the navigator.clipboard.writeText() API (Modern and Preferred)

Most modern browsers now support the navigator.clipboard.writeText() API, which provides a straightforward, promise-based interface. This approach is clean, doesn’t require hidden inputs, and works asynchronously.

import React from 'react';

function CopyTextButton() {
  const textToCopy = 'Hello from React!';

  const handleCopy = () => {
    navigator.clipboard.writeText(textToCopy)
      .then(() => {
        console.log('Text copied to clipboard');
      })
      .catch((err) => {
        console.error('Failed to copy text: ', err);
      });
  };

  return (
    <button onClick={handleCopy}>
      Copy Text
    </button>
  );
}

export default CopyTextButton;

Recommended Courses

Notes

  • Browser Support: Most evergreen browsers (Chrome, Firefox, Edge, Safari) support navigator.clipboard in secure contexts (HTTPS).
  • Asynchronous: You can handle success or errors via .then() and .catch().

2. Using a Temporary Hidden Element (Older/Legacy Approach)

For older browsers that lack support for navigator.clipboard.writeText(), you can manually create a hidden text area (or input), select its contents, and trigger the document.execCommand('copy'). Although this approach is more verbose, it can help ensure compatibility with older environments.

import React from 'react';

function CopyTextButton() {
  const textToCopy = 'Hello from React!';

  const handleCopy = () => {
    const tempInput = document.createElement('textarea');
    tempInput.value = textToCopy;
    document.body.appendChild(tempInput);

    // Select and copy the text
    tempInput.select();
    document.execCommand('copy');

    // Remove the temporary element
    document.body.removeChild(tempInput);

    console.log('Text copied to clipboard (legacy method)');
  };

  return (
    <button onClick={handleCopy}>
      Copy Text (Legacy)
    </button>
  );
}

export default CopyTextButton;

Notes

  • document.execCommand('copy'): This older API isn’t guaranteed to remain forever. It’s still usable but is considered legacy.
  • Security Restrictions: Some browsers may block copying if not triggered by a user action (like a click).

Handling Edge Cases and Best Practices

  1. HTTPS Requirement
    • For navigator.clipboard.writeText(), many browsers only allow clipboard access on secure contexts (HTTPS) or localhost.
  2. User Interaction
    • Browsers typically require a user gesture (e.g., a button click) before allowing a clipboard write operation. Attempting to copy text automatically on page load or without user action may fail.
  3. Feedback
    • Consider showing a toast or inline message (“Copied!”) to inform users the copy was successful.
  4. Error Handling
    • Always .catch() errors or handle them in a try/catch block. Clipboard operations can fail due to browser security settings or missing permissions.

Putting It All Together

For modern browsers:

function CopyTextButton() {
  const textToCopy = 'Some text here';

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(textToCopy);
      alert('Copied to clipboard!');
    } catch (error) {
      alert('Copy failed, please try again.');
    }
  };

  return (
    <button onClick={handleCopy}>
      Copy Text
    </button>
  );
}

For older browser support, fall back to the legacy hidden text area approach. You can also detect support for navigator.clipboard and use the modern or legacy approach accordingly.

Conclusion

  • Use navigator.clipboard.writeText() when possible for a cleaner, promise-based API.
  • Fallback to a hidden text area and document.execCommand('copy') for older browsers.
  • Always trigger copying in response to a user action (like a click).
  • Provide feedback to the user indicating the text was successfully copied.

With these patterns, you’ll be able to reliably copy text to the clipboard across a wide range of environments in your React applications.