0

What is the best way to go to implement a Copy to clipboard functionality in React. When clicking a button you copy some text to the clipboard which you can paste elsewhere.

meez
  • 3,783
  • 5
  • 37
  • 91

1 Answers1

2

You can use the navigator clipoard api, and fallback to the "old" approach if it's not supported

export function copyTextToClipboard(textToCopy) {
  try {
    copyTextNavigatorClipboard(textToCopy);
  } catch (error) {
    // navigator.clipboard.writeText() doesn't work on iOS,
    // so fall back to using the browser "copy" command.
    copyTextDOMElement(textToCopy);
  }
}

function copyTextNavigatorClipboard(textToCopy) {
  navigator.clipboard.writeText(textToCopy);
}

function copyTextDOMElement(textToCopy) {
  let textArea = document.createElement("textArea");
  textArea.value = textToCopy;

  document.body.appendChild(textArea);

  const range = document.createRange();
  range.selectNodeContents(textArea);

  const selection = window.getSelection();
  selection.removeAllRanges();
  selection.addRange(range);

  textArea.setSelectionRange(0, 999999);

  document.execCommand("copy");

  document.body.removeChild(textArea);
}

credit

Reifocs
  • 704
  • 3
  • 16