forked from dair-ai/Prompt-Engineering-Guide
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopy-to-clipboard.tsx
More file actions
50 lines (42 loc) · 1.14 KB
/
copy-to-clipboard.tsx
File metadata and controls
50 lines (42 loc) · 1.14 KB
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
49
50
'use client'
import type { ReactElement } from 'react'
import { useCallback, useEffect, useState } from 'react'
import { CheckIcon } from './check'
import { CopyIcon } from './copy'
import { Button } from './button'
interface CopyToClipboardProps {
getValue: () => string
className?: string
}
export const CopyToClipboard = ({
getValue,
className
}: CopyToClipboardProps): ReactElement => {
const [isCopied, setCopied] = useState(false)
useEffect(() => {
if (!isCopied) return
const timerId = setTimeout(() => {
setCopied(false)
}, 2000)
return () => {
clearTimeout(timerId)
}
}, [isCopied])
const handleClick = useCallback(async () => {
setCopied(true)
if (!navigator?.clipboard) {
console.error('Access to clipboard rejected!')
}
try {
await navigator.clipboard.writeText(getValue())
} catch {
console.error('Failed to copy!')
}
}, [getValue])
const IconToUse = isCopied ? CheckIcon : CopyIcon
return (
<Button onClick={handleClick} className={className}>
<IconToUse className="nextra-copy-icon nx-pointer-events-none nx-h-4 nx-w-4" />
</Button>
)
}