Avoid Manipulating DOM Directly: Instead of creating and appending a temporary text area to the DOM for copying to the clipboard, we can use the Clipboard API, which is cleaner and more modern.
Basic Example
Previous Code:-
const handleCopyToClipboard = (textToCopy) => {
if (!error) {
const tempTextArea = document.createElement("textarea");
tempTextArea.value = textToCopy;
document.body.appendChild(tempTextArea);
tempTextArea.select();
document.execCommand("copy");
document.body.removeChild(tempTextArea);
// Update the copy button state
setIsCopied(true);
} else {
// Display the error (you can adjust the UI as needed)
setIsCopied(false);
alert(`Error: ${error}`);
}
};
Updated Code (More Optimized)
const handleCopyToClipboard = (textToCopy) => {
if (!error) {
navigator.clipboard
.writeText(textToCopy)
.then(() => {
// Update the copy button state
setIsCopied(true);
})
.catch((err) => {
// Handle clipboard write error
console.error("Copy to clipboard failed:", err);
setIsCopied(false);
});
} else {
// Display the error (you can adjust the UI as needed)
setIsCopied(false);
alert(`Error: ${error}`);
}
};
Have you given as much information as possible about the feature?
[X] Yes, I have provided as much as information for the feature
Is there an existing issue for this?
Reference Issues
23
Description
Avoid Manipulating DOM Directly: Instead of creating and appending a temporary text area to the DOM for copying to the clipboard, we can use the Clipboard API, which is cleaner and more modern.
Basic Example
Previous Code:-
Updated Code (More Optimized)
Have you given as much information as possible about the feature?