Pular para o conteúdo
Botão·Grátis

Botão de copiar (React)

Botão em React e TypeScript que copia um texto para a área de transferência. Mostra "Copied" por dois segundos e uma linha de status oculta avisa o leitor de tela. Não precisa de framework de CSS. Em páginas via http sem criptografia, usa o comando de copiar antigo.

Instalação grátis.

Se o PocketCode estiver instalado no seu Android, isto abre a página no app.

Prévia

CopyButton.tsx · 112 linhas
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 prévia está encurtada. O conteúdo completo vem com a instalação.

Mudanças na 1.0.0

Primeira versão.

Relacionados