AshKetchup
AshKetchup

Reputation: 21

Copy Text To Clipboard using ReactJS

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?

Upvotes: 2

Views: 19616

Answers (2)

Shikhar Awasthi
Shikhar Awasthi

Reputation: 1232

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

Upvotes: 1

sabdahtb
sabdahtb

Reputation: 251

you can add the button on the react page :

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

Upvotes: 10

Related Questions