Home > other >  Copy Text To Clipboard using ReactJS
Copy Text To Clipboard using ReactJS

Time:06-04

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?

CodePudding user response:

you can add the button on the react page :

<button onClick={() =>  navigator.clipboard.writeText('Copy this text to clipboard')}>Copy</button>

CodePudding user response:

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");
  }
}}
  • Related