Skip to content

Instantly share code, notes, and snippets.

@Soumyarian98
Created November 17, 2024 22:59
Show Gist options
  • Select an option

  • Save Soumyarian98/63c67b8c7c3f794fa3fabf3a4d0c5027 to your computer and use it in GitHub Desktop.

Select an option

Save Soumyarian98/63c67b8c7c3f794fa3fabf3a4d0c5027 to your computer and use it in GitHub Desktop.
import { useState } from 'react';
function useCopyToClipboard(): [boolean, (text: string) => Promise<void>] {
const [isCopied, setIsCopied] = useState<boolean>(false);
const copyToClipboard = async (text: string): Promise<void> => {
if (!navigator?.clipboard) {
console.warn('Clipboard not supported');
return;
}
try {
await navigator.clipboard.writeText(text);
setIsCopied(true);
setTimeout(() => setIsCopied(false), 2000); // Optional: reset the copied state after 2 seconds
} catch (error) {
console.error('Failed to copy text: ', error);
setIsCopied(false);
}
};
return [isCopied, copyToClipboard];
}
export default useCopyToClipboard;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment