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?

2

2 Answers 2

10

you can add the button on the react page :

<button onClick={() =>  navigator.clipboard.writeText('Copy this text to clipboard')}>Copy</button>
Sign up to request clarification or add additional context in comments.

1 Comment

This seems right, but giving an error in Chrome.
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");
  }
}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.