Copy to Clipboard
The Copy to Clipboard component allows users to quickly copy text to the clipboard without using context menus or keyboard shortcuts.
It’s commonly used to allow users to copy unique identifiers such as tokens and URLs.
note
There are certain circumstances when browser's API to interact with clipboard may throw an error (or reject
the returned Promise), thus we recommend to always provide onError
callback via props. For example, we could show a toast notification "Couldn't copy to the clipboard. Please try again.". See "Handle errors" below for an example.
Example
Usage Rules
Do:
- Use a
snackbar
to notify users when a component wraps an element that will disappear on click. - Whenever possible, use the
Clipboard
icon with a trigger element.
Variants
Toast Notification
To notify users with a toast you need to wrap your component tree with the ToastProvider
.
// App.js
import { ToastProvider } from '@adjust/components';
export default function() {
return (
<ToastProvider>
{...}
</ToastProvider>
);
}
Although you can decide by yourself how to notify users we strongly recommend using a toast only if a trigger element will disappear on click.
Alternatively, you can use the copyToClipboard
callback. You can get it from the useCopyToClipboard
hook.
In that case, you should pass text
and notificationMessage
arguments into the copyToClipboard
function, respectively.
Additionally, this function can optionally receive the onCopy
callback as the third argument.
Tooltip Position
You can use tooltipPosition
prop to specify Tooltip position inside Copy to Clipboard
Handling errors
Browser API to interact with clipboard returns a promise, which can get rejected instead of resolved. Ideally we should handle potential errors, for instance navigator.clipboard.writeText()
rejects when the browser window is not focused.
To reproduce this, you might enable CPU throttling via the DEV tools and click on the copy icon, following it up with immediate change to another window with a hotkey, as otherwise enough time will pass for promise to successfully resolve.
Props
CopyToClipboard
Name | Type | Default |
---|---|---|
notificationMessage * Text to be shown in the notification |
| — |
text * Text to be copied to clipboard |
| — |
notificationType The type of component to be used for notification |
| "tooltip" |
onCopy The callback will be executed after the text has copied |
| — |
onError The callback executed when failed to copy |
| — |
tooltipPosition |
| — |
children The trigger element. |
| — |
zIndex Add z-index rule to the tooltip component |
| "auto" |
* - the prop is required. |