Skip to content

Instantly share code, notes, and snippets.

@KristofferEriksson
Created January 22, 2024 11:32
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save KristofferEriksson/3c743304865aafefcd27005b18cb6a7d to your computer and use it in GitHub Desktop.
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.
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