copy url to clipboard javascript react code example
Example 1: react copy to clipboard button
<buttononClick={() => navigator.clipboard.writeText("Copy this text to clipboard")}>
Copy
</button>
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>
);
}