2

I'm using ReactJS and when a user clicks a Button I want to copy some div content to clipboard.

I can't see why this code does not result in the data being copied to the clipboard. am giving value from redux store when its true am coping content from div

componentDidUpdate(prevProps, prevState, snapshot) {
  console.log("value to copy is-->", this.props.copy);
  var copyText = document.getElementById("myInput");

  /* Select the text field */

  console.log("copyText-->", copyText);
  console.log("document-->", document);
  /* Copy the text inside the text field */
  document.execCommand("copy");
}
thesk
  • 45
  • 8
  • Possible duplicate of [In reactJS, how to copy text to clipboard?](https://stackoverflow.com/questions/39501289/in-reactjs-how-to-copy-text-to-clipboard) also. There are possible solutions there. Otherwise I used many times [clipboard.js](https://clipboardjs.com/) – Lionel T Jul 09 '19 at 09:37

2 Answers2

1

You need to add el.select(); before run copy command.

componentDidUpdate(prevProps, prevState, snapshot) {
    console.log("value to copy is-->",this.props.copy);
    var copyText = document.getElementById("myInput");

    /* Select the text field */

    copyText.select();

    /* Copy the text inside the text field */
    document.execCommand("copy");
}
Le Khiem
  • 541
  • 4
  • 9
0

You can use this package. It is very simple and it will work cross platform.

SimoMatavulj
  • 454
  • 3
  • 9