Lightweight copy to clipboard hook for React
Lightweight copy to clipboard hook for React
use-clipboard-copy
Table of Contents
There are various copy-to-clipboard solutions for Javascript – really good ones, but getting them to work with React can feel a little odd... they don't feel very React-y.
use-clipboard-copy is a lightweight ( {
const url = Utils.formatUrl({ query: { id } });
clipboard.copy(url); // programmatically copying a value
},
[clipboard.copy, id]
);
return ( Copy Link ); }
### Displaying a Temporary Success State
Sometimes it can be helpful to notify the user that the text was successfully copied to the clipboard, usually by displaying a temporary "Copied" state after they trigger the copy action.
By passing the `copiedTimeout` option to `useClipboard()`, you can use `clipboard.copied` as a way to toggle the copied state in the UI.
```jsx
import { useClipboard } from 'use-clipboard-copy';
export default function PublicUrl({ url }) {
const clipboard = useClipboard({
copiedTimeout: 600, // timeout duration in milliseconds
});
return (
);
}Copy to clipboard in browsers can be tricky some times - there are various reasons that can contribute to preventing the copy action from working. Therefore, you should always handle such cases.
By passing an onSuccess and onError callbacks to the useClipboard options, you will be able to handle whether the copy action was performed successfully.
function CopyText() {
const clipboard = useClipboard({
onSuccess() {
console.log('Text was copied successfully!')
},
onError() {
console.log('Failed to copy text!')
}
});
return (
);
}
…
jsx
function ClipboardSupport() {
const clipboard = useClipboard();
return (
);
}useClipboard(options?: UseClipboardOptions): ClipboardAPIuse-clipboard-copy exposes a named export useClipboard which is the hook function itself. It takes an optional options object, and returns an object to control the clipboard.
import { useClipboard } from 'use-clipboard-copy';
function CopyText() {
const clipboard = useClipboard();
return (
// ...
);
}
…
jsx
;
;Optionally, copy takes a string to perform the copy action imperatively (programmatically). When this is used, the target element (if set) will be ignored.
clipboard.copy('a text to copy')} />;target: React.RefObjectA React Ref object used on input and textarea elements that holds the text to be copied.
;isSupported: () => booleanA function that returns a boolean indicating whether the browser supports the clipboard APIs. Useful to deterministically update the UI if the browser does not support the clipboard functionality for whatever reason.
copied: booleanA boolean indicating whether the copy action was just performed. Must be used with the copiedTimeout option. Useful to update the UI to display temporary success state.
This hook is powered by clipboard-copy, the lightweight copy to clipboard for the web.
MIT
No open issues yet, or sync has not completed.