Copy Text From A Div To Clipboard Using Document.execcommand In React
Solution 1:
Document.execCommand
will get deprecated in favor of the modern Clipboard API to interact with clipboard.
Here is how to use Clipboard API:
functionupdateClipboard(newClip) {
navigator.clipboard.writeText(newClip).then(
() => {
setCopySuccess("Copied!");
},
() => {
setCopySuccess("Copy failed!");
}
);
}
functioncopyLink() {
navigator.permissions
.query({ name: "clipboard-write" })
.then((result) => {
if (result.state === "granted" || result.state === "prompt") {
updateClipboard(inputArea.current?.innerText);
}
});
}
Notes about using Clipboard API:
The Clipboard API adds greater flexibility, in that you aren't limited to copying the current selection into the clipboard, but can directly specify what information to place into the clipboard.
Using the API requires that you have the permission "clipboardRead" or "clipboardWrite" in your manifest.json file.
The clipboard-write permission is granted automatically to pages when they are in the active tab. The clipboard-read permission must be requested, which you can do by trying to read data from the clipboard.
Or, to use Document.execCommand
, you should convert the div
into an input
or textarea
(which can be selected) and use CSS to make it look like a div:
functioncopyLink(e) {
inputArea.current?.select();
document.execCommand("copy");
e.target.focus();
setCopySuccess("Copied!");
}
// ...
{shortLink && (
<inputref={inputArea}type="text"className="shorten-text"value={shortLink}
/>
)}
Or, see How to copy text from a div to clipboard if you still want to use div
.
Post a Comment for "Copy Text From A Div To Clipboard Using Document.execcommand In React"