copy to clipboard javascript react code example
Example 1: react copy to clipboard
onClick={() => {navigator.clipboard.writeText(this.state.textToCopy)}}
Example 2: copy text to clipboard reactjs
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');
e.target.focus();
setCopySuccess('Copied!');
};
return (
<div>
{
document.queryCommandSupported('copy') &&
<div>
<button onClick={copyToClipboard}>Copy</button>
{copySuccess}
</div>
}
<form>
<textarea
ref={textAreaRef}
value='Some text to copy'
/>
</form>
</div>
);
}