---
title: "Botón de copiar"
description: "Un botón que copia un texto dado con una sola pulsación y lo confirma, o dice que no ha podido. Lo dibuja Button y, de forma predeterminada, nunca mueve el diseño."
url: "https://tanrei.chnotchy.com/es/components/copy-button/"
last_updated: 2026-10-23T21:17:12.000Z
---

# Botón de copiar

> Un botón que copia un texto dado con una sola pulsación y lo confirma, o dice que no ha podido. Lo dibuja Button y, de forma predeterminada, nunca mueve el diseño.

## Descripción general

Usa un botón de copiar junto a algo que una persona va a pegar en otro lugar: un comando, una clave, una dirección, un valor de color. Espera la respuesta del navegador, muestra una marca de verificación (o una marca de error) durante dos segundos y se lo dice con palabras a la tecnología de apoyo. Un [bloque de código](https://tanrei.chnotchy.com/es/components/code-block/) coloca uno por ti.

### Uso

El botón de copiar es un [botón](https://tanrei.chnotchy.com/es/components/button/) de la variante y el tamaño que indiques. No tiene colores ni medidas propios, así que un sistema de diseño que cambia el estilo de Button cambia con él el de todos los botones de copiar.

Las palabras son tuyas. `label`, `copied-label` y `failed-label` no tienen valores predeterminados, porque Tanrei no incluye textos en ningún idioma.

SwiftUI, Compose, Flutter y React Native están planificados: los nombres que figuran junto a cada plataforma al principio de esta página son los que les da la especificación, y todavía no se distribuye nada para ellos.

**Web**

```html
<!-- De solo icono (el valor predeterminado): recibe su nombre de label. -->
<tanrei-copy-button
  text="npm install @tanrei/web"
  label="Copiar"
  copied-label="Copiado"
  failed-label="No se pudo copiar"
></tanrei-copy-button>

<!-- Con etiqueta: el texto cambia con la forma, y la anchura nunca. -->
<tanrei-copy-button
  icon-only="false"
  variant="tonal"
  text="https://example.com/s/4f2a"
  label="Copiar enlace"
  copied-label="Enlace copiado"
  failed-label="No se pudo copiar"
></tanrei-copy-button>

<!-- Con etiqueta y una anchura que sigue a sus palabras: solo al final de una fila. -->
<tanrei-copy-button
  icon-only="false"
  label-width="fit"
  text="sk-test-0000"
  label="Copiar"
  copied-label="Copiado en el portapapeles"
  failed-label="No se pudo copiar"
></tanrei-copy-button>

<script type="module">
  import '@tanrei/web';

  document.querySelector('tanrei-copy-button').addEventListener('copyfailed', () => {
    // El botón ya ha dicho que no ha podido. Lo que ocurra además es cosa tuya.
  });
</script>
```

**React**

```tsx
import { CopyButton } from '@tanrei/react';

<CopyButton text={command} label="Copiar" copiedLabel="Copiado" failedLabel="No se pudo copiar" onCopyFailed={() => showHelp()} />
```

## Especificaciones

Con `label-width="fit"`, la forma con etiqueta es tan ancha como las palabras que muestra. Cuando cambian, su anchura pasa suavemente a la de las nuevas palabras en `comp.copy-button.motion.resize-duration`, y cambia de inmediato donde el movimiento está reducido. El valor predeterminado sigue siendo `widest`, porque un control que se mueve justo cuando alguien va a pulsarlo se pulsa por error. Usa `fit` solo donde no haya detrás del botón nada que la persona pueda pulsar a continuación, como al final de una fila.

El botón tiene tres formas: en reposo (el glifo `content_copy`), copiado (`check`) y fallido (`error`). Muestra la forma de copiado solo después de que el navegador haya confirmado la copia, y vuelve al reposo tras `comp.copy-button.confirmation.duration` (2 segundos). Una pulsación mientras muestra una confirmación copia y confirma de nuevo.

Nada se mueve cuando cambia la forma. Los tres glifos se dibujan en una misma caja. De forma predeterminada, la forma con etiqueta conserva en todo momento la anchura de su texto más ancho; con `label-width="fit"`, su anchura sigue a sus palabras, como arriba.

El glifo cambia de inmediato, sin movimiento. Los dos segundos son un tiempo para darse cuenta, así que se mantienen donde el movimiento está reducido.

Si el texto cambia mientras el botón muestra «copiado», vuelve al reposo de inmediato: lo que se copió ya no es lo que se copiaría.

Los eventos son `copied` y `copyfailed`. No se llaman `copy`, porque `copy` es el evento del portapapeles del propio documento.

- Category: Actions
- Level: composed
- Listing: default
- Built from: Button
- Page: https://tanrei.chnotchy.com/components/copy-button/
- Spec: https://github.com/chnotchy/tanrei/blob/main/specs/copy-button.spec.json

### Availability

| Design system | Has it | Notes |
| --- | --- | --- |
| Tanrei (`tanrei`) | Yes | — |
| Cupertino (Apple HIG-inspired) (`cupertino`) | Yes | — |
| M3 Expressive-like (Material 3 Expressive-inspired) (`m3-expressive-like`) | Yes | — |
| M3-like (Material 3-inspired) (`m3-like`) | Yes | — |

### Platforms

- Web: the element `<tanrei-copy-button>`, registered by importing `@tanrei/web` (or only its own module, `@tanrei/web/components/copy-button`).
- React: `CopyButton` from `@tanrei/react`.

| Platform | Name | Status |
| --- | --- | --- |
| Web | `tanrei-copy-button` | lagging |
| SwiftUI | `TanreiCopyButton` | planned |
| Jetpack Compose | `TanreiCopyButton` | planned |
| Flutter | `TanreiCopyButton` | planned |
| React Native | `CopyButton` | planned |

Names a platform gives in its own idiom:

| Spec | Web | SwiftUI | Jetpack Compose | Flutter | React Native |
| --- | --- | --- | --- | --- | --- |
| `disabled` (prop) | `disabled` | `disabled` | `enabled` | `enabled` | `disabled` |
| `copied` (event) | `copied` | `onCopied` | `onCopied` | `onCopied` | `onCopied` |
| `copyFailed` (event) | `copyfailed` | `onCopyFailed` | `onCopyFailed` | `onCopyFailed` | `onCopyFailed` |

Statuses: `planned` — In the inventory. Nothing shippable exists yet. `lagging` — An implementation of an earlier spec exists; it has not caught up with the current one. `alpha` — Implemented with tests. The API may still change. `beta` — Feature complete and at parity. Only fixes are expected. `stable` — Covered by semantic versioning. `deprecated` — Still shipped; scheduled for removal.

### Anatomy

- `container`: The button: a Button of the chosen variant and size, drawn from the Button's tokens. It carries the state answer.
- `icon`: The glyph, in one box whatever it shows: content_copy at rest, check when the text has been copied, error when it could not be.
- `label` (optional): The button's text, where it is not icon-only: label at rest, copiedLabel and failedLabel in the two other forms, in a box as wide as the widest of the three (labelWidth widest) or as the one shown (labelWidth fit).

### Props

| Prop | Type | Default | Web attribute | Description |
| --- | --- | --- | --- | --- |
| `text` | `string` | `""` | `text` | The text to copy, exactly as it will be pasted. Plain text only. |
| `label` | `string` | `""` | `label` | What the button does, in the product's language ("Copy", "Copy link", "Copy JSON"): the accessible name of the icon-only form and the visible text of the labelled one. Required. |
| `copiedLabel` | `string` | `""` | `copied-label` | What is announced, and shown in the labelled form, when the text has been copied ("Copied"). Required. |
| `failedLabel` | `string` | `""` | `failed-label` | What is announced, and shown in the labelled form, when the platform refuses the copy ("Could not copy"). Required. |
| `iconOnly` | `boolean` | `true` | `icon-only` | True draws the glyph alone, named by label. False draws the glyph and the label as text. |
| `labelWidth` | `enum`: `widest`, `fit` | `"widest"` | `label-width` | How wide the labelled form's text box is. widest, the default, keeps it as wide as the widest of label, copiedLabel and failedLabel at all times, so the button never changes its width and nothing beside it moves (CPY-7). fit makes it as wide as the text it shows, and eases its width to the new text when the form changes (CPY-19): for a button with nothing after it in its row that a person may press next. Ignored while iconOnly is true. |
| `variant` | `enum`: `filled`, `tonal`, `elevated`, `outlined`, `text` | `"text"` | `variant` | The Button variant it is drawn as. The default, text, is the quiet icon action beside what it copies; a copy that is a view's main action takes another. The values are Button's. |
| `size` | `enum`: `small`, `medium`, `large` | `"medium"` | `size` | The Button size it is drawn at (32 / 40 / 56). The values are Button's. |
| `disabled` | `boolean` | `false` | `disabled` | Prevents the copy; the button is drawn and exposed as a disabled Button. |

### Events

| Event | Description |
| --- | --- |
| `copied` | The platform confirmed that the text is on the clipboard; carries the text. |
| `copyFailed` | The platform refused the copy or has no clipboard to write to; carries the platform's reason where it gives one. |

### States

`enabled`, `hovered`, `focused`, `pressed`, `disabled`

### Accessibility

- Role: `button`
- Labeling: The icon-only form is named by label, which is required, in every form: the name does not change when the glyph does. The labelled form is named by the text it shows. The result is announced through a live region: copiedLabel politely, failedLabel assertively (CPY-5).
- Minimum target size: yes

| Keys | Action |
| --- | --- |
| Tab | Moves focus to the copy button. |
| Enter or Space | Copies the text and confirms it; focus stays on the button. |

- The target is the Button's (BTN-5): at least sys.target.touch for touch and sys.target.pointer for a fine pointer on both axes, whatever size is drawn.
- The confirmation is a status message (WCAG 4.1.3): it reaches assistive technology without moving focus. The glyph change alone would say nothing to a person who cannot see it, and a changed name is not announced on every platform, which is why the icon-only form's name stays and the live region speaks.
- The confirmation is not given by color: the glyph changes shape (check, error) in the Button's own icon color, and the words are announced. No success or error color is used.
- The confirmation returns by itself after comp.copy-button.confirmation.duration. Nothing a person must act on is in it, so no timing control is needed (WCAG 2.2.1); a failure a person must act on is the product's to show, on copyFailed, in something that stays.
- A sighted person using the icon-only form sees the check and, for as long as it shows, the same words in a bubble drawn as a plain Tooltip (CPY-18): the change of a glyph alone can be missed by a person who does not know the check, or who reads the page magnified. The bubble is not read a second time: the announcement of CPY-5 is the one assistive technology hears.
- The labelled form's visible text is its name (WCAG 2.5.3) in every form. By default (labelWidth widest) its width is reserved for the widest of the three texts, so neighbouring controls do not move under a pointer about to press them (CPY-7). labelWidth fit lets the width follow the text — a change the person asked for by pressing, eased over a short motion and at once where motion is reduced (WCAG 2.3.3) — and is for a button that nothing a person may press next stands after; its own box still keeps the minimum target in every form.
- Copying needs the platform's permission and, on the web, a secure page and a press by the person: a copy asked for by script alone may be refused, and is then a failure (CPY-4).

### Behaviour

Requirements in EARS form, each with its stable id.

- **CPY-1** THE copy button SHALL be drawn as a Button (BTN) of its variant and size, from the Button's own tokens in every state — its container, its glyph, its label, its state layer, its outline and elevation, its disabled form — icon-only with the glyph content_copy WHILE iconOnly is true, and with that glyph leading and label as its text otherwise. It SHALL have no color, shape or measure of its own, SHALL extend its hit area as BTN-5 says, and SHALL draw its glyphs through the platform's icon helper, as a Button does.
- **CPY-2** WHEN the copy button is activated by pointer, touch, Enter, Space or assistive technology THE copy button SHALL ask the platform to put text on the clipboard as plain text, exactly as given; it SHALL NOT read the clipboard, SHALL NOT copy anything but text, SHALL NOT move focus, and SHALL NOT show the copied form before the platform has answered. A second activation before that answer SHALL be ignored.
- **CPY-3** WHEN the platform confirms that the text is on the clipboard THE copy button SHALL take the copied form: the glyph check in place of content_copy, in the same box and the same color, and, WHILE iconOnly is false, copiedLabel in place of label; it SHALL emit copied once, carrying the text, and SHALL return to rest comp.copy-button.confirmation.duration after it took the form.
- **CPY-4** IF the platform refuses the copy or has no clipboard to write to THEN THE copy button SHALL take the failed form — the glyph error in the same box and the same color, and, WHILE iconOnly is false, failedLabel in place of label — SHALL emit copyFailed once, and SHALL return to rest comp.copy-button.confirmation.duration after it took the form. It SHALL NOT select the text, open a dialog or try another way by itself: what else happens is the product's, on that event. IF text is empty WHEN the copy button is activated THEN it SHALL copy nothing and take the failed form, and in debug builds report that there was nothing to copy.
- **CPY-5** WHEN the copy button takes the copied form THE copy button SHALL have assistive technology announce copiedLabel once, politely (after what is being read); WHEN it takes the failed form it SHALL have failedLabel announced once, assertively. Every activation SHALL be announced anew, also when the same words were announced a moment before. The announcement SHALL NOT move keyboard or screen-reader focus, and nothing SHALL be announced on the return to rest.
- **CPY-6** WHILE iconOnly is true THE copy button SHALL be named by label in every form: its name does not change with its form, and the form is told by the announcement of CPY-5. WHILE iconOnly is false THE copy button SHALL be named by the text it shows. THE glyph SHALL be kept from assistive technology in every form.
- **CPY-7** THE copy button SHALL NOT move or resize anything when it changes form, but as CPY-19 says WHILE labelWidth is fit: the three glyphs are drawn in one box; WHILE iconOnly is false and labelWidth is widest the label's box SHALL be as wide as the widest of label, copiedLabel and failedLabel at all times, the shown text at its start, and the button's width and height SHALL be the same in every form; its height SHALL be the same in every form whatever labelWidth is; and the copy button SHALL open no popover, menu or other surface of its own but the confirmation of CPY-18, which takes no room.
- **CPY-8** WHEN the copy button is activated WHILE it is in the copied or the failed form THE copy button SHALL copy again as CPY-2 says and, on the platform's answer, take the form that answer gives, emit its event, announce it (CPY-5) and count the duration from that moment.
- **CPY-9** THE copy button SHALL change its glyph and its text at once, without a motion, in both directions (WHILE labelWidth is fit only the width of the text's box moves, as CPY-19 says); the time of comp.copy-button.confirmation.duration is a time to notice and SHALL NOT be shortened or skipped where motion is reduced. WHEN text changes WHILE the copy button is in the copied form THE copy button SHALL return to rest at once: what was copied is no longer what would be.
- **CPY-10** WHILE disabled is true THE copy button SHALL be drawn and exposed as a disabled Button, SHALL copy nothing and SHALL emit nothing; WHEN it becomes disabled WHILE in the copied or the failed form it SHALL return to rest at once.
- **CPY-11** WHILE the system's icon set cannot yet draw a glyph of the copy button (its font is still loading) THE copy button SHALL draw nothing in that glyph's place, never the glyph's name as text, SHALL keep the glyph's box, and SHALL draw the glyph once the set can; label, copiedLabel and failedLabel SHALL still reach assistive technology.
- **CPY-12** WHEN the copy button is pressed by pointer, touch, Enter or Space THE copy button SHALL show the pressed state without delay and SHALL keep it visible for at least sys.motion.duration.press-hold, even when the press ends sooner.
- **CPY-13** WHILE pressed THE copy button SHALL answer as sys.behavior.pressed-feedback names: overlay applies the pressed tokens to the whole container at once; ripple grows the pressed state layer from the point of contact (from the center for keyboard activation); dim applies the pressed opacity to the whole control and draws no state layer; none draws no answer to the press. Under ripple and dim only the container color stays with the state under the press; label, icon, outline, elevation, opacity and shape still come from the pressed tokens. Under none every part stays with the state under the press. The ripple grows over comp.button.motion.feedback-duration with comp.button.motion.state-easing, fades over the state duration of its size (comp.button.motion.state-duration.small, .medium or .large) with comp.button.motion.state-easing once the press has ended and press-hold has passed, and appears whole where motion is reduced.
- **CPY-14** THE copy button SHALL ease its container corners by sys.shape.corner-smoothing (0 is a quarter circle, 0.6 the iOS continuous corner; a platform with only the OS curve draws it for any amount above 0) and show its keyboard focus as sys.behavior.focus-style names (ring or glow); a platform that cannot draw a choice SHALL fall back to the first value and state that in its README.
- **CPY-15** THE copy button SHALL take its layout direction from where it is used — the direction of the nearest ancestor that sets one, and the platform's own where none does — and SHALL have no direction setting of its own; WHEN that direction changes while the copy button is shown THE copy button SHALL draw itself for the new direction at once, without a motion of its own, keeping its form, the time left before it returns to rest and its focus.
- **CPY-16** WHERE the layout direction is right-to-left THE copy button SHALL place its glyph and its label as a Button places a leading icon and a label (BTN-11), and SHALL draw each of its glyphs mirrored left to right exactly when the system's icon set marks that glyph's name as mirrored: the icon helper mirrors the glyph inside its own box, changing neither its place, size, color and fill. THE copy button SHALL NOT mirror a glyph itself.
- **CPY-17** WHILE label, copiedLabel or failedLabel is empty THE copy button SHALL still render and copy, and in debug builds report which is missing: an icon-only button without label has no accessible name, unless the product gives it a name of its own on the element — aria-label, or aria-labelledby naming an element — which it then exposes as its accessible name and does not report missing. WHILE label is not empty THE copy button SHALL expose the name CPY-6 says, over a name the product gives it on the element (aria-label or aria-labelledby). WHEN variant or size names a value the Button does not have in the active design system THE copy button SHALL be drawn with its own default for that prop, and in debug builds report the unknown value.
- **CPY-18** WHEN the copy button takes the copied or the failed form WHILE iconOnly is true THE copy button SHALL show copiedLabel or failedLabel as a plain Tooltip (TIP) of its button — drawn from the Tooltip's own tokens and placed as it places itself, at the top by default — for as long as the form lasts, and SHALL close it at the return to rest; each answer of CPY-8 SHALL show it anew. It SHALL take no focus and no room, move nothing, and SHALL NOT open or close on hover, focus or a long press; it SHALL be closed by Escape and by another tooltip that opens, as any tooltip is, and SHALL be kept from assistive technology, which hears the words once, from the announcement of CPY-5. WHILE iconOnly is false THE copy button SHALL show no such bubble: its label says it.
- **CPY-19** WHILE iconOnly is false and labelWidth is fit THE copy button SHALL make the label's box as wide as the text it shows, and its button as wide as that box and its glyph make it, the text on one line; WHEN the shown text changes — the form changes, or the words of the form shown do — THE copy button SHALL change the box's width from the width it has to the new text's over comp.copy-button.motion.resize-duration with comp.copy-button.motion.resize-easing, keeping its height, its glyph and the start of its text in place and clipping the text at the box's end while the box is narrower than it, and SHALL change the width at once where motion is reduced. THE copy button SHALL take its first width, and a width that changes because the text's face has arrived, at once. A change of form during the motion SHALL continue from the width reached.
- **CPY-20** WHERE the platform has ARIA attributes (the web), WHEN the product sets an aria- attribute on the host, by the attribute or by the ARIA property that reflects it, THE copy button SHALL move it to the data-aria- attribute of the same name, so that the host is no second node with its name, description or state, and SHALL expose it on the element that carries its role — an id reference by the elements it names in the host's tree or a tree around it, an error message as part of the description while the copy button is invalid — except those the copy button owns (aria-pressed, aria-disabled), which it SHALL move and not expose. WHEN the product removes the aria- attribute or its data-aria- twin, or sets the ARIA property that reflects it (ariaLabel, ariaDescribedByElements…) to null, THE copy button SHALL take it off that element. WHEN the product sets an aria- attribute the copy button owns THE copy button SHALL report it in debug builds.

### Tokens

As written in the token documents (DTCG): an alias in braces names the token it takes its value from, which each design system resolves. On the web each token is a CSS custom property: `--tanrei` and the name after `tanrei`, joined by hyphens (`tanrei.comp.copy-button.…` → `--tanrei-comp-copy-button-…`).

#### `tanrei.comp.copy-button`

| Token | Type | Value |
| --- | --- | --- |
| `comp.copy-button.confirmation.duration` | `duration` | `2000ms` |
| `comp.copy-button.motion.resize-duration` | `duration` | `{tanrei.sys.motion.role.resize.default}` |
| `comp.copy-button.motion.resize-easing` | `cubicBezier` | `{tanrei.sys.motion.easing.spatial}` |

### Qué dibuja la web de otra manera

- La copia usa `navigator.clipboard.writeText`. Necesita una página segura (HTTPS o localhost) y una pulsación de la persona. Donde el navegador no tiene portapapeles o se niega, el botón toma la forma de fallido. No hay ningún mecanismo alternativo.
- Los dos eventos se propagan hacia arriba y no cruzan un shadow root.

## Pautas

### De solo icono o con etiqueta

| Forma | Qué muestra | Úsalo cuando |
| --- | --- | --- |
| **De solo icono** | El glifo y, mientras muestra la marca de verificación, las palabras en una pequeña burbuja encima | Junto a lo que copia: un comando, un bloque de código, un valor en una fila |
| **Con etiqueta** | El glifo y las palabras, que cambian con la forma | La copia es una de las acciones de la vista, o las palabras importan a todo el mundo |

### Recomendado

- Di en la etiqueta qué se copia cuando no resulte obvio por su lugar: «Copiar enlace», «Copiar JSON».
- Escucha `copyfailed` y muestra algo que permanezca, como el texto seleccionado en un campo, cuando la persona necesite conseguir el texto de todos modos.
- Conserva la variante `text` para un botón de copiar situado junto a su contenido. Elige otra variante cuando copiar sea la acción principal de la vista.
- Conserva la anchura predeterminada cuando detrás de un botón de copiar con etiqueta haya algo que la persona pueda pulsar a continuación. Elige `label-width="fit"` solo donde no haya nada.

### Evita

- No muestres el botón solo al pasar el cursor. Así no se puede encontrar con el tacto.
- No abras un tooltip ni un snackbar propios por una copia correcta. El botón ya la confirma, también con palabras.
- No lo uses para copiar nada que no sea texto.

## Accesibilidad

### De qué se encarga el componente

- Es un botón, con el indicador de foco de Button, su objetivo mínimo y sus teclas (Enter y Espacio).
- La forma de solo icono recibe su nombre de `label` en todas las formas. El nombre no cambia cuando cambia el glifo.
- El resultado se anuncia mediante una región activa: `copied-label` de forma cortés y `failed-label` de forma asertiva, en cada pulsación y sin mover el foco.
- La forma de solo icono muestra también esas palabras en una burbuja dibujada como un [tooltip](https://tanrei.chnotchy.com/es/components/tooltip/) plain, mientras dura la confirmación. No toma el foco, no se lee una segunda vez y Escape la cierra.
- La confirmación es una figura y unas palabras, no un color.
- En un diseño de derecha a izquierda, el glifo de copiar se refleja, como indica el conjunto de iconos. La marca de verificación y la marca de error, no.
- La forma con etiqueta conserva su anchura de forma predeterminada, así que nada se mueve bajo un puntero a punto de pulsar. Con `label-width="fit"`, la anchura pasa suavemente a la de las nuevas palabras, y cambia de inmediato donde el movimiento está reducido.

### Qué debes hacer tú

- Da las tres etiquetas, en el idioma de tu producto. Un botón de solo icono sin `label` no tiene nombre accesible.
- Ocúpate tú de lo que sigue a un fallo cuando la persona no deba perder el texto.
