2

I need to copy some text to clipboard (we're using React JS, but a more general approach would be fine too), but the issue I'm running into currently is that the text needs to exist in the Document in order to select / copy it.

The text we want to copy to clipboard isn't something that we want actually displayed on the page. I tried looking at a similar question: react: copy component state value to clipboard without dummy element.

Basically doing something like this:

function copyToClipboard(text){
    var dummy = document.createElement("input");
    document.body.appendChild(dummy);
    dummy.setAttribute('value', createdMyTextHere);
    // dummyElement.style.display = "none" - doesn't work because then we can't select from it
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}

I did what the OP did, but the issue is that in some cases (like under extreme load or if there's some sort of delay between when the element is added and when its removed from the document) the element will show up very briefly and then disappear, causing a bit of a flicker on the screen.

I tried setting the element to be hidden or setting display:none but hidden still results in the space being created for the element and display:none results in us not being able to select from the element at all.

Any suggestions on how to get around this issue?

CustardBun
  • 3,457
  • 8
  • 39
  • 65

2 Answers2

2

I would suggest this. Its an npm package that lets you copy any text to clipboard of the client. To copy any text:

<CopyToClipboard text={'Your custom text here'}
  onCopy={() => this.setState({copied: true})}>
  <span>Copy to clipboard with span</span>
</CopyToClipboard>
Dani
  • 556
  • 7
  • 23
  • The examples I've seen for that npm package seem to imply that you need an actual input field containing what you want to copy from in order to copy text to the clipboard. Which is my main issue - we aren't copying from any visible field on the page. Am I misunderstanding the documentation? Can you put arbitrary non-rendered text onto the page? – CustardBun Jul 10 '20 at 17:51
  • I don't really understand what you want to copy to the clipboard. You can put any string in the text field. I have updated the answer – Dani Jul 10 '20 at 17:55
  • 1
    Ah, I think I misunderstood the example. It looks ilke this would work too. Thanks! – CustardBun Jul 10 '20 at 18:15
1

You can use a combination of opacity, position and z-index:

function copyToClipboard(text){
    var dummy = document.createElement("input");
    dummy.style.position = "fixed";
    dummy.style.opacity = 0;
    dummy.style.zIndex = -1;
    
    document.body.appendChild(dummy);
    dummy.setAttribute('value', createdMyTextHere);    
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}
Anurag Srivastava
  • 14,077
  • 4
  • 33
  • 43