Copy Button
beta
The CopyButton component provides a button that copies text to the clipboard when clicked. It includes visual feedback to indicate when the text has been copied successfully. The name prop can be a string or a function that returns a string, allowing for dynamic text generation.
Copy Button with Function Callback
Below are examples showing how to use a function callback for dynamic text generation, including both success and error cases:
Usage
Basic Usage
import { CopyButton } from '@harnessio/ui/components'
return ( <CopyButton name="Text to copy" />)Using Function Callback (Success Case)
You can pass a function to name that returns the text to copy. This is useful when the text needs to be computed dynamically:
import { CopyButton } from '@harnessio/ui/components'
const getTextToCopy = () => { // Compute or retrieve the text dynamically return `Current timestamp: ${Date.now()}`}
return ( <CopyButton name={getTextToCopy} />)Using Function Callback (Error Handling)
If the function throws an error, a toast notification will be displayed to the user:
import { CopyButton } from '@harnessio/ui/components'
const getTextToCopy = () => { // This might throw an error in some cases if (someCondition) { throw new Error('Failed to retrieve text') } return 'Text to copy'}
return ( <CopyButton name={getTextToCopy} />)When an error occurs, a toast with the title “Failed to copy” and the error message will be shown to the user.
API Reference
Prop | Required | Default | Type |
|---|---|---|---|
| name | true | string | (() => string) | |
| className | false | string | |
| buttonVariant | false | 'custom' | ButtonProps['variant'] |
| iconSize | false | 'sm' | 'md' | 'xs' | 'sm' | '2xs' | 'lg' | 'xl' |
| onClick | false | (e: MouseEvent) => void | |
| color | false | 'white' | 'gray' | 'white' | 'success' |