click button copy to clipboard using react code example
Example 1: 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>
);
}
Example 2: react copy to clipboard
onClick={() => {navigator.clipboard.writeText(this.state.textToCopy)}}