I want to copy specific content from the page, rather than the HTML itself. And the execCommand method, is deprecated, I tried with useRef(), but no progress
How i solve this?
const div = useRef(null);
const [copySuccess, setCopySuccess] = useState(false);
const copyToClipboard = () => {
const html = div.current.innerHTML.trim();
navigator.clipboard.writeText(html)
setCopySuccess(true);
};
<div>
{user.name && (
<button
type="submit"
style={{
margin-top: '30px',
margin-bottom: '10px',
height: '45px',
width: '85px',
background-color: '#1d71a5',
color: '#fff',
border: 'none',
border-radius: '5px',
font-size: '16px',
cursor: 'pointer',
}}
onClick={copyToClipboard}
>
Copy
</button>
)}
{copySuccess && (
<div style={{ color: 'green' }}> ✔︎ Copy with Success! </div>
)}
</div>
I want to copy the signature email content
Refrence: https://vdt-email-signature.vercel.app
I tried to use the hook useRef, i tried to use this method :
const copyDivToClipboard = () => {
const range = document.createRange()
const selectedDiv = document.getElementById('generated-div')
range?.selectNode(selectedDiv as Node)
window?.getSelection()?.removeAllRanges() // clear current selection
window?.getSelection()?.addRange(range) // to select text
document.execCommand('copy')
window?.getSelection()?.removeAllRanges() // to deselect
alert('Message copied to clipboard!')
}
But is a deprecated method.
And so far I have no progress.