Copy text to the clipboard on button click in React.js?

Answered
suparman21 asked this question 1 year, 5 months ago
suparman21 on Dec 13, 2021

When a button is clicked, I want to copy some text to the user's clipboard.

Can someone show me how I can do this?

2 suggested answers
nick on Dec 16, 2021

Here's some React.js code that should do the trick:

import React from "react"
import copy from "copy-to-clipboard"

class ComponentName extends React.Component {
  copyTextToClipboard() {
    copy("Text copied to the clipboard.")
  }

  render() {
    return (
      <button onClick={this.copyTextToClipboard}>Copy</button>
    )
  }
}

export default ComponentName

This displays a <button> element that copies "Text copied to the clipboard" to the user's clipboard when it's clicked on.

The copy-to-clipboard NPM package is used to add the text to the user's clipboard.

0 replies
coderguy on Dec 16, 2021

Here's a function you can use when the button is clicked in your React.js page:

  copyTextToClipboard(text) {
    let input = document.createElement("textarea")
    input.innerHTML = text
    document.body.appendChild(input)
    input.select()
    let result = document.execCommand("copy")
    document.body.removeChild(input)
    return result
  }

This function creates a textarea element (not visible to the user) and fills it with the text content provided to the function as a parameter.

Then, the execCommand("copy") method is used to copy the text content to the user's clipboard.

Once the text is copied, the textarea element is removed from the dom.

0 replies
Answered