7

In my project there is one usage case: user click one button and then copy some data to clipboard for next step.

The copied data is related to the clicked button, and is stored in the component state.

I do some search, and find the potential solution as following:

function copyToClipboard(text){
    var dummy = document.createElement("input");
    document.body.appendChild(dummy);
    dummy.setAttribute('value', text);
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}

to some extend, we need to create a dummy element, set the copied data to the dummy element and select the element, then execute the execCommand(copy) method.

is it possible to do this without creating dummy element? I know there are some react plugin about clipboard, but I just want to use vanilla javascript. thank you

Chris Bao
  • 2,418
  • 8
  • 35
  • 62

1 Answers1

5

Your solution works well.

If the value you want to copy is not yet rendered on the DOM, your Document.createElement('input')... method is a good way to create a document node that Document knows about, but that is not visible to the user. Once you use .createElement() you can then call execCommand() on it to copy the value to the clipboard.

The execCommand() method is exposed by HTML5's Document. This means Document has to know about the node you are targeting before you can use the method (this is called Selection).

However, if you want to copy text from an element already rendered on the dom (e.g an input in a form), you could use React's callback ref. Here's a good example of using ref to do this. It's pretty simple, so using a library is likely to be overkill.

Jordan Rolph
  • 1,242
  • 1
  • 10
  • 14