react-copy-to-clipboard-hook
v1.0.0
Published
A simple React hook for copying text to clipboard with success feedback
Maintainers
Readme
react-copy-to-clipboard-hook
A simple, lightweight React hook for copying text to clipboard with success feedback and error handling.
Features
- 🎯 Simple and intuitive API
- ✅ Success feedback with customizable duration
- ❌ Error handling with detailed error messages
- 🔄 Manual reset functionality
- 📦 Tiny bundle size (< 2KB)
- 🎨 TypeScript support
- 🧪 Well tested
Installation
npm install react-copy-to-clipboard-hookyarn add react-copy-to-clipboard-hookpnpm add react-copy-to-clipboard-hookUsage
Basic Usage
import { useCopyToClipboard } from 'react-copy-to-clipboard-hook';
function MyComponent() {
const { copy, copied, error } = useCopyToClipboard();
const handleCopy = () => {
copy('Hello, World!');
};
return (
<div>
<button onClick={handleCopy}>
{copied ? 'Copied!' : 'Copy Text'}
</button>
{error && <p style={{ color: 'red' }}>Error: {error.message}</p>}
</div>
);
}With Custom Options
import { useCopyToClipboard } from 'react-copy-to-clipboard-hook';
function MyComponent() {
const { copy, copied, error, reset } = useCopyToClipboard({
successDuration: 3000, // Show success for 3 seconds
onSuccess: (text) => console.log('Copied:', text),
onError: (error) => console.error('Copy failed:', error),
});
const handleCopy = async () => {
const success = await copy('Hello, World!');
if (success) {
// Handle success
}
};
return (
<div>
<button onClick={handleCopy}>Copy</button>
<button onClick={reset}>Reset</button>
{copied && <span>✅ Copied!</span>}
{error && <span>❌ {error.message}</span>}
</div>
);
}Real-world Example
import { useCopyToClipboard } from 'react-copy-to-clipboard-hook';
function ShareButton({ url }: { url: string }) {
const { copy, copied, error } = useCopyToClipboard({
successDuration: 2000,
onSuccess: () => {
// Could show a toast notification
console.log('URL copied to clipboard!');
},
});
return (
<button
onClick={() => copy(url)}
disabled={copied}
style={{
backgroundColor: copied ? '#4CAF50' : '#2196F3',
color: 'white',
padding: '8px 16px',
border: 'none',
borderRadius: '4px',
cursor: copied ? 'default' : 'pointer',
}}
>
{copied ? '✅ Copied!' : '📋 Copy URL'}
</button>
);
}API Reference
useCopyToClipboard(options?)
Parameters
options(optional): Configuration object
Options
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| successDuration | number | 2000 | Duration in milliseconds to show success state |
| onSuccess | (text: string) => void | undefined | Callback fired when copy succeeds |
| onError | (error: Error) => void | undefined | Callback fired when copy fails |
Returns
| Property | Type | Description |
|----------|------|-------------|
| copy | (text: string) => Promise<boolean> | Function to copy text to clipboard |
| copied | boolean | Whether the last copy operation was successful |
| error | Error \| null | Error object if the last copy operation failed |
| reset | () => void | Function to reset the copied and error states |
copy(text: string): Promise<boolean>
Copies the provided text to the clipboard.
- Parameters:
text- The text to copy - Returns: Promise that resolves to
trueif successful,falseotherwise
Browser Support
This hook uses the modern Clipboard API, which is supported in:
- Chrome 66+
- Firefox 63+
- Safari 13.1+
- Edge 79+
The hook will gracefully handle unsupported browsers by returning an error.
Requirements
- React 16.8.0 or higher (for hooks support)
- A secure context (HTTPS) for the Clipboard API to work
TypeScript
This package is written in TypeScript and includes type definitions. No additional @types package is needed.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
MIT © [ Matthias Egbele ]
Changelog
1.0.0
- Initial release
- Basic clipboard functionality with success feedback
- TypeScript support
- Comprehensive test coverage
