I am attempting to copy text from a div
after the URL is shortened.
I have placed a ref
value in the div
that will render the shortend URL. But, I am getting error:
TypeError: inputArea.input.select() is not a function.
I am not sure how to reference the text within the div.
import { useCallback, useEffect, useRef, useState } from "react";
const Shorten = () => {
const [copySuccess, setCopySuccess] = useState('');
const inputArea = useRef(null);
function copyLink(e){
inputArea.current.select();
document.execCommand('copy');
e.target.focus();
setCopySuccess('Copied!');
};
{isPending && <div className="loading-text">Loading...</div>}
{shortLink && <div ref={inputArea} className="shorten-text">{shortLink}</div>}
<hr></hr>
<div>
<button className="shorten-it" onClick={copyLink} >Copy</button>
{copySuccess}
</div>
</section>
Document.execCommand
will get deprecated in favor of the modern Clipboard API to interact with clipboard .
Here is how to use Clipboard API:
function updateClipboard(newClip) {
navigator.clipboard.writeText(newClip).then(
() => {
setCopySuccess("Copied!");
},
() => {
setCopySuccess("Copy failed!");
}
);
}
function copyLink() {
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:
function copyLink(e) {
inputArea.current?.select();
document.execCommand("copy");
e.target.focus();
setCopySuccess("Copied!");
}
// ...
{shortLink && (
<input
ref={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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.