use-clipboard-pro
v1.0.1
Published
A bulletproof React clipboard hook with global history, ARIA support, and iOS fallbacks.
Maintainers
Readme
✂️ use-clipboard-pro
A bulletproof React clipboard hook engineered for production. It features global state sync, accessibility (ARIA) announcements, and legacy iOS fallbacks.
Most clipboard hooks (use-clipboard-copy, @mantine/hooks) are simple useState wrappers that fail silently on older devices, ignore screen readers, and lose history between components. use-clipboard-pro fixes all of that in < 1.5kB.
✨ Why this is different
- Global History Sync: Powered by an
@xstate/storefinite state machine. If you copy in a Modal, your Navbar instantly knows about it. - 100% Accessible: Automatically injects an
aria-liveregion to announce "Copied!" to VoiceOver/NVDA screen readers. - Bulletproof Fallbacks: Uses an invisible
<textarea>injection for older iOS Safari versions and local HTTP dev environments that block the modernnavigator.clipboardAPI. - SSR Ready: Safely checks for
windowbefore executing.
📦 Installation
npm install use-clipboard-pro
# or
yarn add use-clipboard-pro🚀 Quick Start
TypeScript
import { useClipboardPro } from 'use-clipboard-pro';
export function App() {
const { copy, copied, status, history, clearHistory } = useClipboardPro({
clearAfter: 2500, // Reset the 'copied' boolean after 2.5s
announce: true, // Enable ARIA screen-reader announcements
});
return (
<div>
<button onClick={() => copy('npm install use-clipboard-pro')}>
{copied ? '✅ Copied!' : '📋 Copy Install Command'}
</button>
{status === 'error' && <p>Permission denied!</p>}
<h3>Your Global Copy History:</h3>
<ul>
{history.map((item, i) => (
<li key={i}>{item}</li>
))}
</ul>
<button onClick={clearHistory}>Clear History</button>
</div>
);
}🧠 API Reference
useClipboardPro(options?: UseClipboardOptions)
Props
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| clearAfter | number | 2000 | Milliseconds before the copied state resets to false. |
| announce | boolean | true | Whether to announce the copy event to screen readers. |
Returns
| Property | Type | Description |
|----------|------|-------------|
| copy(text: string) | Promise<boolean> | Triggers the copy action. Returns success status. |
| copied | boolean | True if successfully copied. Resets after clearAfter ms. |
| status | 'idle' \| 'copied' \| 'error' | The strict current state of the clipboard machine. |
| history | string[] | Array of the last 5 unique copied strings. Synced globally. |
| clearHistory() | void | Clears the global copy history. |
