Created
January 22, 2024 11:32
-
-
Save KristofferEriksson/3c743304865aafefcd27005b18cb6a7d to your computer and use it in GitHub Desktop.
Custom React hook for effortless text copying to clipboard! It handles copy status with a customizable timer and error management.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useCallback, useState } from "react"; | |
// Custom hook to copy text to clipboard | |
const useCopyToClipboard = (timeoutDuration: number = 1000) => { | |
const [copied, setCopied] = useState(false); | |
const [error, setError] = useState<Error | null>(null); | |
const copyToClipboard = useCallback( | |
async (text: string) => { | |
try { | |
await navigator.clipboard.writeText(text); | |
setCopied(true); | |
setError(null); | |
setTimeout(() => setCopied(false), timeoutDuration); | |
} catch (err) { | |
setError(err instanceof Error ? err : new Error("Failed to copy text")); | |
} | |
}, | |
[timeoutDuration] | |
); | |
return { copied, error, copyToClipboard }; | |
}; | |
export default useCopyToClipboard; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment