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?