useCopyToClipboard()

This React hook provides a copy method to save a string in the clipboard and the copied value (default: null).

If anything doesn't work, it prints a warning in the console and the value will be null.

The Hook

1import { useState } from 'react'
2
3type CopiedValue = string | null
4type CopyFn = (text: string) => Promise<boolean> // Return success
5
6function useCopyToClipboard(): [CopiedValue, CopyFn] {
7 const [copiedText, setCopiedText] = useState<CopiedValue>(null)
8
9 const copy: CopyFn = async text => {
10 if (!navigator?.clipboard) {
11 console.warn('Clipboard not supported')
12 return false
13 }
14
15 // Try to save to clipboard then save it in the state if worked
16 try {
17 await navigator.clipboard.writeText(text)
18 setCopiedText(text)
19 return true
20 } catch (error) {
21 console.warn('Copy failed', error)
22 setCopiedText(null)
23 return false
24 }
25 }
26
27 return [copiedText, copy]
28}
29
30export default useCopyToClipboard

Usage

1import React from 'react'
2
3import { useCopyToClipboard } from 'usehooks-ts'
4
5export default function Component() {
6 const [value, copy] = useCopyToClipboard()
7 return (
8 <>
9 <h1>Click to copy:</h1>
10 <div style={{ display: 'flex' }}>
11 <button onClick={() => copy('A')}>A</button>
12 <button onClick={() => copy('B')}>B</button>
13 <button onClick={() => copy('C')}>C</button>
14 </div>
15 <p>Copied value: {value ?? 'Nothing is copied yet!'}</p>
16 </>
17 )
18}

See a way to make this page better?
Edit there »