'How can I copy text to clipboard with ReactJS?

I am building a React web app that converts a text into an array. I want the user to click on the final output and be able to copy it on the clipboard.

I am following the of many websites and tutorial. I am very new to ReactJS and I don't know what's wrong with my code!

This is the function I

copyToClipboard() {
const {array} = this.state

const textToCopy = "const myArray =" + JSON.stringify(array)

textToCopy.select()
document.execCommand("copy")

this.setState({copySuccess: true})
}

The function is called by this button. The button works fine:

      <button onClick={this.copyToClipboard.bind(this)} id="copy-to-clipboard" className="btn btn-normal">Copy to clipboard</button>

I think the problem is in this part of the function below, but I don't know how to fix it!

textToCopy.select()
document.execCommand("copy")

Link to the whole app + code:

https://codepen.io/Nerdifico/pen/MWKPdNX?editors=0010



Solution 1:[1]

You should use a DOM element from which to copy from. This is an example with textarea. You can't call select on string value.

Solution 2:[2]

const copyToClipboard = (content: any) => {
  const el = document.createElement('textarea');
  el.value = content;
  document.body.appendChild(el);
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
};

Here is my solution, it contains 3 steps:

  • Create an empty textarea element
  • Assign the value your want to copy to it and exec copy command
  • Remove the textarea you have created

Solution 3:[3]

As @Rosen mentioned you should use copy on DOM element

Something like this

 <textarea
        ref={(textarea) => this.textArea = textarea}
        value='Some text to copy'
      />

and then in your function call it

copyToClipboard = (e) => {
    this.textArea.select();
    document.execCommand('copy');

  };

Solution 4:[4]

export const CopyTextIcon: React.FC = () => {
  function copyToClipboard() {
    const tempInput = document.createElement('input')
    tempInput.value = 'text'
    document.body.appendChild(tempInput)
    tempInput.select()
    document.execCommand('copy')
    document.body.removeChild(tempInput)
  }

  return (
    <div onClick={()=>copyToClipboard('topRight')}>
       <img src="/images/ic-SHARE.svg" alt="share" />
    </div>
  )
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rosen Dimov
Solution 2 Neoflies
Solution 3 Navitas28
Solution 4 Fateme Norouzi