Component
Copy Button
Clipboard copy with transient feedback. Uses the async Clipboard API with an execCommand fallback. On success, swaps the icon to a check and the label to "Copied", then reverts. An `aria-live` region announces the copied state.
- Component
- React
- TSX
- Tailwind CSS
- MIT
Preview
Live component
9:41 100%
devsnips.dev/library/react/components/buttons/copy-button/ fluid · no fixed width 100%
Install
Add to your project
npx devsnips add React/Components/Buttons/copy-button React/Components/Buttons/copy-button import { useCallback, useRef, useState } from "react";
import type { ButtonHTMLAttributes } from "react";
/* DevSnips React — CopyButton
* Clipboard copy with transient feedback. Async Clipboard API + execCommand
* fallback. aria-live announces the copied state; icon + label confirm
* success without relying on color alone.
*/
export type ButtonSize = "xs" | "sm" | "md" | "lg" | "xl";
export type CopyVariant = "outline" | "secondary" | "ghost" | "solid";
export interface CopyButtonProps
extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, "onClick"> {
value: string;
label?: string;
copiedLabel?: string;
resetMs?: number;
onCopy?: (value: string) => void;
variant?: CopyVariant;
size?: ButtonSize;
}
function cx(...parts: Array<string | false | null | undefined>): string {
return parts.filter(Boolean).join(" ");
}
const SIZES: Record<ButtonSize, string> = {
xs: "h-7 gap-1 px-2 text-xs [&_svg]:size-[14px]",
sm: "h-8 gap-1.5 px-3 text-xs [&_svg]:size-[14px]",
md: "h-9 gap-2 px-3.5 text-[13px] [&_svg]:size-4",
lg: "h-10 gap-2 px-4 text-[13px] [&_svg]:size-[18px]",
xl: "h-11 gap-2 px-5 text-sm [&_svg]:size-5",
};
const VARIANTS: Record<CopyVariant, string> = {
outline: "border-[var(--ds-color-border-strong)] bg-transparent text-[var(--ds-color-foreground)] hover:bg-[var(--ds-color-surface-hover)] active:bg-[var(--ds-color-surface-active)]",
secondary: "border-[var(--ds-color-border)] bg-[var(--ds-color-secondary)] text-[var(--ds-color-secondary-foreground)] hover:bg-[var(--ds-color-surface-active)] active:bg-[var(--ds-color-surface-active)]",
ghost: "border-transparent bg-transparent text-[var(--ds-color-foreground)] hover:bg-[var(--ds-color-surface-hover)] active:bg-[var(--ds-color-surface-active)]",
solid: "border-transparent bg-[var(--ds-color-primary)] text-[var(--ds-color-primary-foreground)] hover:bg-[color-mix(in_srgb,var(--ds-color-primary)_88%,#000)] active:bg-[color-mix(in_srgb,var(--ds-color-primary)_80%,#000)]",
};
function useCopy(resetMs: number) {
const [copied, setCopied] = useState(false);
const t = useRef<ReturnType<typeof setTimeout> | null>(null);
const copy = useCallback(async (text: string) => {
try {
if (navigator.clipboard && window.isSecureContext) { await navigator.clipboard.writeText(text); }
else {
const ta = document.createElement("textarea");
ta.value = text;
ta.style.position = "fixed";
ta.style.opacity = "0";
document.body.appendChild(ta);
ta.select();
document.execCommand("copy");
document.body.removeChild(ta);
}
setCopied(true);
if (t.current) clearTimeout(t.current);
t.current = setTimeout(() => setCopied(false), resetMs);
} catch { /* clipboard unavailable */ }
}, [resetMs]);
return [copied, copy] as const;
}
export function CopyButton({
value,
label = "Copy",
copiedLabel = "Copied",
resetMs = 2000,
onCopy,
variant = "outline",
size = "sm",
className,
type = "button",
...rest
}: CopyButtonProps) {
const [copied, copy] = useCopy(resetMs);
async function handle() { await copy(value); onCopy?.(value); }
return (
<button
type={type}
className={cx("inline-flex select-none items-center justify-center whitespace-nowrap rounded-[var(--ds-radius-sm)] border font-medium leading-none transition-colors duration-150 ease-out motion-reduce:transition-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--ds-color-focus-ring)] disabled:pointer-events-none disabled:opacity-50", VARIANTS[variant], SIZES[size], className)}
onClick={handle}
aria-label={`${copied ? copiedLabel : label}: ${value}`}
{...rest}
>
<svg className="h-[1em] w-[1em] shrink-0" viewBox="0 0 24 24" fill="none" aria-hidden="true">
{copied
? <path d="M20 6 9 17l-5-5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
: <><rect x="9" y="9" width="12" height="12" rx="2" /><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" /></>}
</svg>
<span>{copied ? copiedLabel : label}</span>
<span className="sr-only" role="status" aria-live="polite">{copied ? copiedLabel : ""}</span>
</button>
);
}
export default CopyButton; /* DevSnips React — JavaScript parity build.
* Same API, behavior, and classes as code.tsx; TypeScript types removed.
* Regenerated from code.tsx — edit code.tsx and re-run the generator.
*/
import { useCallback, useRef, useState } from "react";
function cx(...parts) {
return parts.filter(Boolean).join(" ");
}
const SIZES = {
xs: "h-7 gap-1 px-2 text-xs [&_svg]:size-[14px]",
sm: "h-8 gap-1.5 px-3 text-xs [&_svg]:size-[14px]",
md: "h-9 gap-2 px-3.5 text-[13px] [&_svg]:size-4",
lg: "h-10 gap-2 px-4 text-[13px] [&_svg]:size-[18px]",
xl: "h-11 gap-2 px-5 text-sm [&_svg]:size-5"
};
const VARIANTS = {
outline: "border-[var(--ds-color-border-strong)] bg-transparent text-[var(--ds-color-foreground)] hover:bg-[var(--ds-color-surface-hover)] active:bg-[var(--ds-color-surface-active)]",
secondary: "border-[var(--ds-color-border)] bg-[var(--ds-color-secondary)] text-[var(--ds-color-secondary-foreground)] hover:bg-[var(--ds-color-surface-active)] active:bg-[var(--ds-color-surface-active)]",
ghost: "border-transparent bg-transparent text-[var(--ds-color-foreground)] hover:bg-[var(--ds-color-surface-hover)] active:bg-[var(--ds-color-surface-active)]",
solid: "border-transparent bg-[var(--ds-color-primary)] text-[var(--ds-color-primary-foreground)] hover:bg-[color-mix(in_srgb,var(--ds-color-primary)_88%,#000)] active:bg-[color-mix(in_srgb,var(--ds-color-primary)_80%,#000)]"
};
function useCopy(resetMs) {
const [copied, setCopied] = useState(false);
const t = useRef(null);
const copy = useCallback(async (text) => {
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
} else {
const ta = document.createElement("textarea");
ta.value = text;
ta.style.position = "fixed";
ta.style.opacity = "0";
document.body.appendChild(ta);
ta.select();
document.execCommand("copy");
document.body.removeChild(ta);
}
setCopied(true);
if (t.current) clearTimeout(t.current);
t.current = setTimeout(() => setCopied(false), resetMs);
} catch {
}
}, [resetMs]);
return [copied, copy];
}
export function CopyButton({
value,
label = "Copy",
copiedLabel = "Copied",
resetMs = 2e3,
onCopy,
variant = "outline",
size = "sm",
className,
type = "button",
...rest
}) {
const [copied, copy] = useCopy(resetMs);
async function handle() {
await copy(value);
onCopy?.(value);
}
return <button
type={type}
className={cx("inline-flex select-none items-center justify-center whitespace-nowrap rounded-[var(--ds-radius-sm)] border font-medium leading-none transition-colors duration-150 ease-out motion-reduce:transition-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--ds-color-focus-ring)] disabled:pointer-events-none disabled:opacity-50", VARIANTS[variant], SIZES[size], className)}
onClick={handle}
aria-label={`${copied ? copiedLabel : label}: ${value}`}
{...rest}
>
<svg className="h-[1em] w-[1em] shrink-0" viewBox="0 0 24 24" fill="none" aria-hidden="true">
{copied ? <path d="M20 6 9 17l-5-5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /> : <><rect x="9" y="9" width="12" height="12" rx="2" /><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" /></>}
</svg>
<span>{copied ? copiedLabel : label}</span>
<span className="sr-only" role="status" aria-live="polite">{copied ? copiedLabel : ""}</span>
</button>;
}
export default CopyButton; # Copy Button
Clipboard copy with transient feedback. Uses the async Clipboard API with an execCommand fallback. On success, swaps the icon to a check and the label to "Copied", then reverts. An `aria-live` region announces the copied state.
## Installation
This component requires **React** and **Tailwind CSS**. Drop `code.tsx` (or `code.jsx` for JavaScript projects) into your project. Tailwind utility classes are included directly in the component, so no separate CSS file is required.
The component consumes the DevSnips semantic design tokens through Tailwind arbitrary values (for example `bg-[var(--ds-color-primary)]`). Define the `--ds-*` tokens once in your theme — see [React/DESIGN_TOKENS.md](../../../DESIGN_TOKENS.md) for the full token spec.
## Usage
```tsx
<CopyButton value={projectId} />
```
## JavaScript
A `code.jsx` build is provided for projects that ship plain JSX. It exposes the same API and behavior as `code.tsx` — only the TypeScript types are removed.
## Props
| Prop | Type | Default |
|---|---|---|
| `value` | `string` | — (text to copy) |
| `label` | `string` | `"Copy"` |
| `copiedLabel` | `string` | `"Copied"` |
| `resetMs` | `number` | `2000` |
| `onCopy` | `(value: string) => void` | — |
| `variant` | `outline \| secondary \| ghost \| solid` | `outline` |
| `size` | `ButtonSize` | `sm` |
Plus all native `ButtonHTMLAttributes<HTMLButtonElement>`.
## Variants
outline (default) · secondary · ghost · solid.
## Sizes
xs (28px) · sm (32px) · **md (36px, default)** · lg (40px) · xl (44px). Horizontal padding scales 8 → 20px; icons scale 14 → 20px. Default is `sm`.
## States
default · hover · focus-visible · **copied** (check icon + "Copied" label + `aria-live` announcement, reverts after `resetMs`).
## Accessibility
Renders a native `<button>`. Focus-visible ring uses `color.focus-ring`. Loading sets `aria-busy` and disables to prevent double-submit. Disabled never removes the affordance (reduced opacity, not hidden). Meets the 44px touch target at lg/xl. An `aria-live="polite"` region announces "Copied" so screen readers hear the result. `aria-label` includes the value being copied. Success is conveyed by icon + label change, not color alone.
## Styling
Tailwind classes are included directly in the component and consume the DevSnips semantic design tokens (`--ds-*`) via arbitrary values. The button themes with the surface automatically in light and dark mode. No component-specific CSS file is needed.
## Design Tokens
See [React/DESIGN_TOKENS.md](../../../DESIGN_TOKENS.md) for the authoritative token specification. This button uses the semantic color, radius, and motion tokens; define them once in your project theme and every button in the family stays in sync.
## Notes
Always pair with the value displayed nearby (a code/ID row) so the copy target is unambiguous. Gracefully degrades when the Clipboard API is unavailable. 100 lines UTF-8 · LF · Spaces: 2
Continue browsing