---
title: CopyButton
description: Copy a value to the clipboard and show a short copied state.
package: moraine
version: 0.11.0
repository: https://github.com/subframe7536/moraine
---

# CopyButton

> Copy a value to the clipboard and show a short copied state.

## Anatomy

```text
CopyButton [component; slot=root]
├── icon [slot]
└── label [slot]
```

## Usage

Use CopyButton to copy a string or `ClipboardItem` to the clipboard from a single control. It writes
through `navigator.clipboard` and falls back to `document.execCommand('copy')` when the Clipboard API
is missing or the write fails. After a copy it holds a `copied` or `failed` state for `resetDelay`,
then returns to `idle`.

```tsx
import { CopyButton } from 'moraine'

export function Example() {
  return <CopyButton value="https://moraine.subf.dev" />
}
```

### Value

`value` accepts a string, a `ClipboardItem`, a `ClipboardItem[]`, a promise of either, or a function
that returns one. A function runs on every click, and a promise is awaited first. If either fails,
the copy fails and `onCopyError` receives the error. The `execCommand` fallback copies text only.

```tsx
<CopyButton value={async () => (await fetch('/api/share-link')).text()}>Copy share link</CopyButton>
```

### With text and icons

Pass children to render a labeled button. Without children, CopyButton renders a square icon-only
button at the matching icon size. `iconPosition` places the icon before (`leading`, default) or after
(`trailing`) the label. Children can also be a function that receives the copy state, including
`isCopied`, `isError`, and `status`.

```tsx
<CopyButton value="npm i moraine">Copy Install Command</CopyButton>
```

### Accessible name

The button's `aria-label` is `Copy to clipboard`, and `Copied to clipboard` while copied. Override
the wording through the provider messages, or set `aria-label` to name what is copied. After a failed
copy the button sets `aria-invalid` until `resetDelay` elapses.

### Variant, tone, and size

`variant` (`solid`, `soft`, `outline`, `ghost`), `tone`, and `size` work as on
[Button](https://moraine.subf.dev/components/button.md), but CopyButton defaults to the `ghost` variant and `neutral` tone.
Inside a [ButtonGroup](https://moraine.subf.dev/components/button-group.md), it inherits the group's `size`, `tone`, and
`variant` (except `link`).

### Feedback duration and icons

`resetDelay` sets how long the `copied` or `failed` state holds, in milliseconds; it defaults to 2000. Set `icon` for the idle glyph and `copiedIcon` for the copied glyph. Pass `icon={false}` to hide
the icon. Use `onCopySuccess`, `onCopyError`, and `onStatusChange` to react to the result.

```tsx
<CopyButton
  value="https://example.com"
  resetDelay={3000}
  icon="i-lucide:clipboard"
  copiedIcon="i-lucide:check-check"
/>
```

### Headless hook: `createCopy`

[createCopy](https://moraine.subf.dev/hooks/create-copy.md) from `moraine/utils` runs the same copy logic without a button. It
returns `copy` and `reset`, plus the `isCopied`, `isError`, `status`, `error`, and `isSupported`
accessors.

```tsx
import { createCopy } from 'moraine/utils'

const copy = createCopy({
  resetDelay: 2500,
  onCopySuccess: (value) => console.log('Copied:', value),
})

// Trigger programmatically:
copy.copy('Hello world')
```

## Examples

### Copy a command from a read-only field

Pair a read-only `Input` with an icon-only CopyButton so the user can read and copy the command.

```tsx
import { CopyButton, Input } from 'moraine'

export function CopyButtonUsage() {
  const code = 'pnpm add moraine'

  return (
    <div class="flex gap-2 max-w-sm w-full items-center">
      <Input value={code} readOnly class="font-mono" />
      <CopyButton value={code} />
    </div>
  )
}
```

### Swap icons and hold the copied state longer

Set `icon` and `copiedIcon` for the two states, and raise `resetDelay` to keep the confirmation
visible.

```tsx
import { CopyButton, Input } from 'moraine'

export function CustomIcons() {
  const token = 'ghp_exampleTokenValue1234567890'

  return (
    <div class="flex gap-2 max-w-sm w-full items-center">
      <Input value={token} readOnly type="password" class="font-mono" />
      <CopyButton
        value={token}
        icon="i-lucide:clipboard"
        copiedIcon="i-lucide:check-check"
        resetDelay={3000}
        aria-label="Copy personal access token"
      />
    </div>
  )
}
```

### Change the label while copied

Pass a function child to read `state.isCopied` and show different label text after a copy. Set
`iconPosition="trailing"` to move the icon after the label.

```tsx
import { CopyButton } from 'moraine'

export function WithLabel() {
  const curlCommand = 'curl -s https://moraine.subf.dev/install.sh | bash'

  return (
    <div class="flex flex-wrap gap-3 items-center justify-center">
      <CopyButton value={curlCommand} variant="soft" size="sm">
        {(state) => (state.isCopied ? 'Copied to clipboard!' : 'Copy curl command')}
      </CopyButton>

      <CopyButton value={curlCommand} variant="outline" size="sm" iconPosition="trailing">
        Copy snippet
      </CopyButton>
    </div>
  )
}
```

## API Reference

### Attributes

| Attributes | Slot | Description |
| --- | --- | --- |
| `data-copied` | `copy-button`, `copy-button-icon` | Present while the copied state is active. |
| `data-disabled` | `copy-button` | Present when the component, slot, or item is disabled. |

### Props

Props for the CopyButton component.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| copiedIcon | IconT.Name \| undefined | 'icon-check' | Icon displayed during the `'copied'` state, in place of `icon`. |
| disabled | boolean \| undefined | — | Disabled state, including for non-button polymorphic roots. |
| icon | IconT.Name \| undefined | 'icon-copy' | Icon displayed in the idle and failed states. Pass `false` (or `null`) to hide the icon;<br>without children the button then has no visible content. |
| iconPosition | 'leading' \| 'trailing' \| undefined | 'leading' | Position of the copy indicator icon relative to the label. Has no effect without children. |
| onCopyError | ((error: unknown) => void) \| undefined | — | Called when the copy fails, with the thrown or rejected error, or an `Error` when the<br>clipboard could not be written. The button then has `aria-invalid` until `resetDelay`<br>elapses. |
| onCopySuccess | ((data: CopyData) => void) \| undefined | — | Called after the copy succeeds, with the resolved data that was written (after awaiting a<br>promise or calling a function `value`). |
| onStatusChange | ((details: { isCopied: boolean; status: CopyStatus }) => void) \| undefined | — | Called on every status change: `'idle'` when a copy starts, then `'copied'` or `'failed'`,<br>and `'idle'` again after `resetDelay`. `isCopied` is `true` only for `'copied'`. |
| resetDelay | number \| undefined | 2000 | Delay in milliseconds before the `'copied'` or `'failed'` status returns to `'idle'`. While<br>the `'copied'` status is active the icon switches to `copiedIcon` and the default<br>`aria-label` changes to the localized "copied" message. |
| size | 'xs' \| 'sm' \| 'md' \| 'lg' \| 'xl' \| 'icon-xs' \| 'icon-sm' \| 'icon-md' \| 'icon-lg' \| 'icon-xl' \| undefined | 'md' | Button size, including icon-only sizes. |
| tone | Tone \| undefined | 'neutral' | Color tone while uncopied. |
| value* | CopySource | — | What to copy on click: a string, a `ClipboardItem`, a `ClipboardItem[]`, a `Promise` of<br>either, or a function returning one. A function is called on every click and a promise is<br>awaited first; if it rejects or throws, the copy fails and `onCopyError` receives the error.<br>Non-string data is written with `navigator.clipboard.write`; the `execCommand` fallback can<br>only copy text. |
| variant | 'solid' \| 'soft' \| 'outline' \| 'ghost' \| undefined | 'ghost' | Visual treatment while uncopied. |
| as | T \| undefined | 'button' | Element or component to render as. |
| children | JSX.Element \| Component<ChildrenRenderProps> \| undefined | — | Content or render function receiving the copy state.<br>A render function must declare its parameter, even when unused. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| classes | Classes \| undefined | — | Family slot class defaults for this instance. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |
| styles | Styles \| undefined | — | Family slot style defaults for this instance. |

**`value` example**

```tsx
import { CopyButton } from 'moraine'

<CopyButton
  value={async () => (await fetch('/api/share-link')).text()}
  onCopyError={(error) => console.error(error)}
>
  Copy share link
</CopyButton>
```
