@project44-manifest/react
Version:
Manifest Design System react components
31 lines (25 loc) • 836 B
text/typescript
import React from 'react';
type CopiedValue = string | null;
type CopyFn = (text: string) => Promise<boolean>;
export function useCopyToClipboard(): { copiedText: CopiedValue; copy: CopyFn } {
const [copiedText, setCopiedText] = React.useState<CopiedValue>(null);
const copy: CopyFn = async (text) => {
if (!navigator?.clipboard) {
// eslint-disable-next-line no-console
console.warn('Clipboard not supported');
return false;
}
// Try to save to clipboard then save it in the state if worked
try {
await navigator.clipboard.writeText(text);
setCopiedText(text);
return true;
} catch (error) {
// eslint-disable-next-line no-console
console.warn('Copy failed', error);
setCopiedText(null);
return false;
}
};
return { copiedText, copy };
}