1<button
2 onClick={() => navigator.clipboard.writeText('Copy this text to clipboard')}
3>
4 Copy
5</button>
1 <buttononClick={() => navigator.clipboard.writeText("Copy this text to clipboard")}>
2 Copy
3</button>
1<button
2 onClick={() => navigator.clipboard.writeText('Copy this text to clipboard')}
3>
4 Copy
5</button>
6
1import React, { useRef, useState } from 'react';
2
3export default function CopyExample() {
4
5 const [copySuccess, setCopySuccess] = useState('');
6 const textAreaRef = useRef(null);
7
8 function copyToClipboard(e) {
9 textAreaRef.current.select();
10 document.execCommand('copy');
11 // This is just personal preference.
12 // I prefer to not show the the whole text area selected.
13 e.target.focus();
14 setCopySuccess('Copied!');
15 };
16
17 return (
18 <div>
19 {
20 /* Logical shortcut for only displaying the
21 button if the copy command exists */
22 document.queryCommandSupported('copy') &&
23 <div>
24 <button onClick={copyToClipboard}>Copy</button>
25 {copySuccess}
26 </div>
27 }
28 <form>
29 <textarea
30 ref={textAreaRef}
31 value='Some text to copy'
32 />
33 </form>
34 </div>
35 );
36}
1onClick={() => {navigator.clipboard.writeText(this.state.textToCopy)}}
2
3<button onClick={() => navigator.clipboard.writeText('Copy this text to clipboard')}
4>
5 Copy
6</button>