forked from EddieHubCommunity/BioDrop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClipboardCopy.js
48 lines (43 loc) · 1.3 KB
/
ClipboardCopy.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import React, { useState } from "react";
import { onlyText } from "react-children-utilities";
const ClipboardCopy = ({ children }) => {
const [isCopied, setIsCopied] = useState(false);
async function copyTextToClipboard(text) {
if ("clipboard" in navigator) {
return await navigator.clipboard.writeText(text);
} else {
return document.execCommand("copy", true, text);
}
}
const handleCopyClick = async () => {
try {
await copyTextToClipboard(onlyText(children));
setIsCopied(true);
setTimeout(() => {
setIsCopied(false);
}, 1500);
} catch (error) {
console.log(err);
}
};
return (
<div className="relative">
<div className="absolute flex items-center space-x-2 top-0 right-0 m-2">
<button
type="button"
aria-label="Copy to Clipboard"
onClick={handleCopyClick}
className="transition rounded-md flex items-center justify-center text-center px-2 focus:outline-none fade-in group-hover:flex"
>
{isCopied ? (
<span className="text-green-500 text-sm">Copied!</span>
) : (
<span className="text-gray-500 text-sm">Copy</span>
)}
</button>
</div>
{children}
</div>
);
};
export default ClipboardCopy;