-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseCopyToClipboard.js
35 lines (27 loc) · 938 Bytes
/
useCopyToClipboard.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
const useCopyToClipboard = (text, notifyTimeout = 2500) => {
const [copyStatus, setCopyStatus] = useState('inactive')
const copy = useCallback(() => {
navigator.clipboard.writeText(text).then(
() => setCopyStatus('copied'),
() => setCopyStatus('failed'),
)
}, [text])
useEffect(() => {
if (copyStatus === 'inactive') {
return
}
const timeoutId = setTimeout(() => setCopyStatus('inactive'), notifyTimeout)
return () => clearTimeout(timeoutId)
}, [copyStatus])
return [copyStatus, copy]
}
const CopyUrlButton = ({ url }) => {
const [copyUrlStatus, copyUrl] = useCopyToClipboard(url)
const buttonText = 'Copy URL'
if (copyUrlStatus === 'copied') {
buttonText = 'Copied'
} else if (copyUrlStatus === 'failed') {
buttonText = 'Copy failed!'
}
return <button onClick={copyUrl}>{buttonText}</button>
}