Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In reactJS, how to copy text to clipboard?

I'm using ReactJS and when a user clicks a link I want to copy some text to the clipboard.

I am using Chrome 52 and I do not need to support any other browsers.

I can't see why this code does not result in the data being copied to the clipboard. (the origin of the code snippet is from a Reddit post).

Am I doing this wrong? Can anyone suggest is there a "correct" way to implement copy to clipboard using reactjs?

copyToClipboard = (text) => {   console.log('text', text)   var textField = document.createElement('textarea')   textField.innerText = text   document.body.appendChild(textField)   textField.select()   document.execCommand('copy')   textField.remove() } 
like image 957
Duke Dougal Avatar asked Sep 14 '16 23:09

Duke Dougal


People also ask

How do I copy text to clipboard?

Select the first item that you want to copy, and press CTRL+C. Continue copying items from the same or other files until you have collected all of the items that you want. The Office Clipboard can hold up to 24 items.

How do I copy text from a Div in react?

Inside that function, we hold the <textarea> element in an el variable and select its value with the el. select() method. And with the value selected, we use the document. execCommand("copy") method to copy the value to the user's clipboard.


2 Answers

Use this simple inline onClick function on a button if you want to programatically write data to the clipboard.

onClick={() => {navigator.clipboard.writeText(this.state.textToCopy)}} 
like image 66
Gary Vernon Grubb Avatar answered Oct 01 '22 19:10

Gary Vernon Grubb


I personally don't see the need for a library for this. Looking at http://caniuse.com/#feat=clipboard it's pretty widely supported now, however you can still do things like checking to see if the functionality exists in the current client and simply hide the copy button if it doesn't.

import React from 'react';  class CopyExample extends React.Component {    constructor(props) {     super(props);      this.state = { copySuccess: '' }   }    copyToClipboard = (e) => {     this.textArea.select();     document.execCommand('copy');     // This is just personal preference.     // I prefer to not show the whole text area selected.     e.target.focus();     this.setState({ copySuccess: 'Copied!' });   };    render() {     return (       <div>         {          /* Logical shortcut for only displaying the              button if the copy command exists */          document.queryCommandSupported('copy') &&           <div>             <button onClick={this.copyToClipboard}>Copy</button>              {this.state.copySuccess}           </div>         }         <form>           <textarea             ref={(textarea) => this.textArea = textarea}             value='Some text to copy'           />         </form>       </div>     );   }  }      export default CopyExample; 

Update: Rewritten using React Hooks in React 16.7.0-alpha.0

import React, { useRef, useState } from 'react';  export default function CopyExample() {    const [copySuccess, setCopySuccess] = useState('');   const textAreaRef = useRef(null);    function copyToClipboard(e) {     textAreaRef.current.select();     document.execCommand('copy');     // This is just personal preference.     // I prefer to not show the whole text area selected.     e.target.focus();     setCopySuccess('Copied!');   };    return (     <div>       {        /* Logical shortcut for only displaying the            button if the copy command exists */        document.queryCommandSupported('copy') &&         <div>           <button onClick={copyToClipboard}>Copy</button>            {copySuccess}         </div>       }       <form>         <textarea           ref={textAreaRef}           value='Some text to copy'         />       </form>     </div>   ); } 
like image 40
Nate Avatar answered Oct 01 '22 19:10

Nate