Button·Free
Copy button (React)
A React and TypeScript button that copies a text to the clipboard. It shows "Copied" for two seconds and a hidden status line tells screen readers. No CSS framework is needed. On pages served over plain http it falls back to the older copy command.
Free to install.
If PocketCode is installed on your Android device, this opens the page in the app.
Preview
CopyButton.tsx · 112 lines
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'This preview is shortened. You get the full content when you install it.
Changes in 1.0.0
First version.