useClipboard
The useClipboard
hook provides a simple way to copy text to the clipboard and manage the copied state in a React component.
Add the utility
npx @ivnatsr/ezreact add use-clipboard
import { useState, useCallback } from 'react'
export function useClipboard(resetCopyAfterMs = 300) { const [copied, setCopied] = useState(false)
const copyToClipboard = useCallback( async (text) => { try { await navigator.clipboard.writeText(text) setCopied(true) setTimeout(() => { setCopied(false) }, resetCopyAfterMs) } catch { console.error('Failed to copy text to clipboard') } }, [resetCopyAfterMs] )
return { copied, copyToClipboard }}
import { useState, useCallback } from 'react'
export function useClipboard(resetCopyAfterMs: number | undefined = 300) { const [copied, setCopied] = useState(false)
const copyToClipboard = useCallback( async (text: string) => { try { await navigator.clipboard.writeText(text) setCopied(true) setTimeout(() => { setCopied(false) }, resetCopyAfterMs) } catch { console.error('Failed to copy text to clipboard') } }, [resetCopyAfterMs] )
return { copied, copyToClipboard }}
Return
This hook returns an object containing the following properties:
copied
: A boolean that indicates whether the text has been successfully copied to the clipboard.copyToClipboard
: A function to copy the passed text to the clipboard.
Parameters
resetCopyAfterMs
(optional): A number representing the duration (in milliseconds) after which thecopied
state will reset tofalse
. The default value is300 ms
.
Example
import { useClipboard } from './path/to/use-clipboard'
const ClipboardExample = () => { const { copied, copyToClipboard } = useClipboard(300)
const handleCopy = () => { copyToClipboard('Hello, World!') };
return ( <div> <button onClick={handleCopy}>Copy Text</button> {copied && <span>Text copied to clipboard!</span>} </div> )}
export default ClipboardExample