2

I've been stuck on this issue for a while now and couldn't find anything to help me, so I would love if someone experienced could help me out on this.

lets say I have this const:

const test = "Hello World".

How can I have an onClick function on a button, where when I click it copies the string of test to the users clipboard?

AshKetchup
  • 21
  • 1
  • 1
  • 2
  • Does this answer your question? [In reactJS, how to copy text to clipboard?](https://stackoverflow.com/questions/39501289/in-reactjs-how-to-copy-text-to-clipboard) – Jacob Stephenson Jun 03 '22 at 22:54
  • You can use [`navigator.clipboard.writeText`](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/writeText) or use `document.execCommand("copy")` to support older browsers. I once created [a library](https://copy-js.glitch.me/) a while ago if you're interested. – code Jun 03 '22 at 22:59

2 Answers2

8

you can add the button on the react page :

<button onClick={() =>  navigator.clipboard.writeText('Copy this text to clipboard')}>Copy</button>
sabdahtb
  • 231
  • 1
  • 3
1

To copy a text on clipboard you can use navigator.clipboard and document.execCommand() in older browsers.

onClick={async () => {
  if ("clipboard" in navigator) {
    await navigator.clipboard.writeText("Text which you want to copy");
  } else {
    document.execCommand("copy", true, "Text which you want to copy");
  }
}}
Shikhar Awasthi
  • 1,172
  • 1
  • 3
  • 13