0

In my react project I try to copy a text to clipboard. In the function, I try to create a hidden input, select it and exec "copy" in the document object as seen below:

const copyToClipboard = (textToCopy) => {
   console.log('textToCopy', textToCopy); // Outputs
   let input = document.createElement("input");
       input.setAttribute("type", "hidden");
       input.setAttribute("name", "temp_copy_input")
       input.setAttribute("value", textToCopy);
       input.select()
       console.log('input', input) // outputs object successfully
       document.execCommand("copy");
           input.remove();
}

All console.log work fine, but it doesn't seem to copy the input value.

What am I missing?

Note: I think it's not a duplicate. There's a little detail I missed here, appending the input to the document.

tolga
  • 2,462
  • 4
  • 31
  • 57
  • You can try doing a `try catch` block on your `document.execCommand("copy")` to see if you get any error while trying to copy your text. `document.execComand` also returns a `boolean` value indicating whether if your operation succeeded or not. – junwen-k Nov 11 '19 at 13:06
  • Very interesting but it returns true. – tolga Nov 11 '19 at 13:08
  • Possible duplicate of [In reactJS, how to copy text to clipboard?](https://stackoverflow.com/questions/39501289/in-reactjs-how-to-copy-text-to-clipboard) – denyzprahy Nov 11 '19 at 13:10

1 Answers1

3

This will work for you

var input = document.createElement("input");
    document.body.appendChild(input);
    input.value = textToCopy
    input.select();
    document.execCommand("copy");
    document.body.removeChild(input);

OR

var dummy = document.createElement("textarea");
document.body.appendChild(dummy);
dummy.value = textToCopy
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
Narendra Chouhan
  • 2,291
  • 1
  • 15
  • 24