Lightweight copy to clipboard hook for React
npm install use-clipboard-copy
- Motivation📖 Table of Contents
- Getting Started
- Usage
- Copying Text of Another Target Element
- Copying Text Imperatively (Without a Target Element)
- Displaying a Temporary Success State
- Handling Success and Errors
- Browser Support
- API
- useClipboard(options?: UseClipboardOptions): ClipboardAPI
- UseClipboardOptions
- copiedTimeout?: number
- onSuccess?: () => void
- onError?: () => void
- selectOnCopy?: boolean
- selectOnError?: boolean
- ClipboardAPI
- copy: (text?: string) => void
- target: React.RefObject
- isSupported: () => boolean
- copied: boolean
- Acknowledgements
- License
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 (< 1KB) React hook that makes it possible to add a copy-to-clipboard functionality to your React application with very little code! A simple implementation looks like this:
``js`
function CopyText() {
const clipboard = useClipboard();
return (
);
}
P.S. You can do more than that with use-clipboard-copy. Keep reading!
To get started, add use-clipboard-copy to your project:
``
npm install --save use-clipboard-copy
Please note that use-clipboard-copy requires react@^16.8.0 as a peer dependency.
A simple copy-to-clipboard interface consists of two parts:
- The target, an element who holds the value to be copied, usually an input.copy
- The action.
`jsx
import { useClipboard } from 'use-clipboard-copy';
export default function PublicUrl({ url }) {
const clipboard = useClipboard();
return (
$3
It is also possible to perform a copy action imperatively (programmatically). For example, a copy-to-clipboard interface may consist of a single copy button without any additional inputs or values displayed to the user. By passing a string to the
clipboard.copy action, the specified string will be copied to the clipboard.`jsx
import { useClipboard } from 'use-clipboard-copy';export default function PublicUrl({ id }) {
const clipboard = useClipboard();
const handleClick = React.useCallback(
() => {
const url = Utils.formatUrl({ query: { id } });
clipboard.copy(url); // programmatically copying a value
},
[clipboard.copy, id]
);
return (
);
}
`$3
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 (
);
}
`$3
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.`js
function CopyText() {
const clipboard = useClipboard({
onSuccess() {
console.log('Text was copied successfully!')
},
onError() {
console.log('Failed to copy text!')
}
});
return (
);
}
`In case the
copy action fails, useClipboard will handle that gracefully by selecting the target input instead so that users can copy the text manually. This behavior can be disabled by passing selectOnError: false to the clipboard options.Browser Support
use-clipboard-copy is supported in all browsers that supports the native clipboard APIs, including major browsers such as Chrome, Firefox, Edge, Safari, IE11.This hook provides an
isSupported method that you can use to check for browser support and update the UI accordingly:`jsx
function ClipboardSupport() {
const clipboard = useClipboard();
return (
{clipboard.isSupported()
? "yay! copy-to-clipboard is supported"
: "meh. copy-to-clipboard is not supported"}
);
}
`API
$3
use-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.`js
import { useClipboard } from 'use-clipboard-copy';function CopyText() {
const clipboard = useClipboard();
return (
// ...
);
}
`$3
useClipboard takes an optional object with the following properties:copiedTimeout?: number
- onSuccess?: () => void
- onError?: () => void
- selectOnCopy?: boolean
- selectOnError?: boolean####
copiedTimeout?: numbercopied state upon a successful copy action.####
onSuccess?: () => voidA callback function that will be called upon a successful copy action.
####
onError?: () => voidA callback function that will be called when the copy action fails.
####
selectOnCopy?: booleanDefaults to
false.target element (if set) will be selected upon a successful copy action.####
selectOnError?: booleanDefaults to
true.target element (if set) will be selected when the copy action fails.$3
useClipboard returns an object with the following properties:copied: boolean
- copy: (text?: string) => void
- isSupported: () => boolean
- target: React.RefObject####
copy: (text?: string) => voidA method that will be used to preform the copy action. If it's used without passing a string, the
copy action will use the text of the target element (if set).`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.`jsx
`####
target: React.RefObjectA React Ref object used on input and textarea elements that holds the text to be copied.
`jsx
;
`####
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