Botón·Gratis
Botón de copiar (React)
Botón de React y TypeScript que copia un texto al portapapeles. Muestra «Copied» dos segundos y una línea de estado oculta avisa al lector de pantalla. No necesita framework de CSS. En páginas servidas por http sin cifrar usa el comando de copiar antiguo.
Se instala gratis.
Si tienes PocketCode instalado en tu Android, esto abre la página en la app.
Vista previa
CopyButton.tsx · 112 líneas
import { useEffect, useRef, useState, type ButtonHTMLAttributes, type CSSProperties } from 'react';
// React button that copies a text to the clipboard and tells the user it worked.
// No CSS framework: it takes the text colour of its parent; pass className or style to restyle it.
// <CopyButton text={inviteLink} />
// <CopyButton text={code}>Copy code</CopyButton>
//
// The label changes to "Copied" for two seconds and a hidden status line tells screen readers.
// Over plain http (no secure context) the Clipboard API is missing, so it falls back to a hidden textarea.
type Status = 'idle' | 'copied' | 'failed';
export interface CopyButtonProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'onClick'> {
/** What goes to the clipboard. */
text: string;
/** How long "Copied" stays on the button, in milliseconds. */
resetAfterMs?: number;
/** Called after a successful copy, for analytics or a toast. */
onCopied?: () => void;
}
const baseStyle: CSSProperties = {
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
minWidth: 44,
minHeight: 44,
padding: '8px 16px',
border: '1px solid currentColor',
borderRadius: 8,
background: 'transparent',
color: 'inherit',
font: 'inherit',
fontWeight: 600,
cursor: 'pointer',
};
const visuallyHidden: CSSProperties = {
position: 'absolute',
width: 1,
height: 1,
margin: -1,
padding: 0,
overflow: 'hidden',
clip: 'rect(0 0 0 0)',
whiteSpace: 'nowrap',
border: 0,
};
export function CopyButton({
text,
resetAfterMs = 2000,
onCopied,
children = 'Copy',
type = 'button',
style,
...rest
}: CopyButtonProps) {
const [status, setStatus] = useState<Status>('idle');
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
// Do not leave a timer running after the button is gone.
useEffect(() => () => clearTimeout(timer.current), []);
async function handleClick() {
clearTimeout(timer.current);
try {
await copyText(text);
setStatus('copied');
onCopied?.();
} catch {
setStatus('failed');
}
timer.current = setTimeout(() => setStatus('idle'), resetAfterMs);
}
const label = status === 'copied' ? 'Copied' : status === 'failed' ? 'Copy failed' : children;
const announcement =
status === 'copied'
? 'Copied to the clipboard'Esta vista previa está recortada. El contenido completo llega al instalarlo.
Cambios en la 1.0.0
Primera versión.