useClipboard

Exports Size
loading...
Gzip Size
loading...
Brotli Size
Source Code
View on GitHub
Docs
Edit this page

Handle copying content to clipboard with user-friendly feedbacks.

Usage

import { useClipboard } from 'foxact/use-clipboard';
import { notifications } from '@mantine/notifications';
 
const Demo = () => {
  const { copy, copied, error } = useClipboard({
    // optional, default to 1000, the duration of the copied state after copying
    timeout: 1000,
    // optional, default to false, whether to use `window.prompt` as fallback when native copy method failed
    usePromptAsFallback: false,
    // optional. When `window.prompt` is used as a fallback, this text will be shown in the prompt dialog
    promptFallbackText: 'Failed to copy to clipboard automatically, please manually copy the text below.',
    // optional. Triggers when copy failed and `usePromptAsFallback` is not enabled
    onCopyError(e) {
      notifications.show({ message: 'Failed to copy!' });
    }
  });
 
  return (
    <button onClick={useCallback(() => copy('sukka'), [copy])}>
      {copied ? 'Copied' : 'Copy'}
    </button>
  );
}