useCopyToClipboard

Copy text to the clipboard and show a "copied" state for a short time.

useCopyToClipboard copies a string with the Clipboard API and sets isCopied to true for a set time afterwards.

Import#

typescript
import { useCopyToClipboard } from "@reactberry/system";
import type { useCopyToClipboardProps } from "@reactberry/system";

Usage#

typescript
"use client";

import { useCopyToClipboard } from "@reactberry/system";
import { Button } from "@reactberry/system/elements";

export default function CopyButton({ value }: { value: string }) {
  const { isCopied, copyToClipboard } = useCopyToClipboard({ timeout: 1500 });

  return (
    <Button variant="ghost" onClick={() => copyToClipboard(value)}>
      {isCopied ? "Copied" : "Copy"}
    </Button>
  );
}

Examples#

Custom timeout#

Set timeout to change how long isCopied stays true. Here the confirmation stays for 5 seconds.

npm install @reactberry/system

API#

typescript
function useCopyToClipboard({ timeout }: useCopyToClipboardProps): {
  isCopied: boolean;
  copyToClipboard: (value: string) => void;
}

Parameters#

PropTypeDefaultDescription
options*
useCopyToClipboardProps
—

Options object. Pass {} to use the defaults.

options.timeout
number
2000

How long isCopied stays true after a copy, in milliseconds.

Returns#

PropTypeDefaultDescription
isCopied
boolean
—

true after a successful copy, until the timeout ends.

copyToClipboard
(value: string) => void
—

Copies value with navigator.clipboard.writeText.

Accessibility#

  • The hook only tracks state and announces nothing. To announce a successful copy to screen readers, render the message in an aria-live region.

Notes#

  • The options object is required: call useCopyToClipboard({}) for the default timeout. Calling it with no argument throws.
  • Nothing happens for an empty string, during server rendering, or when navigator.clipboard.writeText is unavailable (for example on non-HTTPS pages).
  • A failed copy (for example, permission denied) is not caught and does not change isCopied.
  • Each copy starts a new timer without clearing the previous one, so after repeated copies isCopied turns false when the first timer ends.