Back to Code Bytes
2 min read
copyText()

Description

The copyText fn uses navigator.clipboard.writeText to asynchronously write the given string to the system clipboard. If the operation fails (for example, due to browser permissions), it catches the error and logs a message to the console.

Code Byte

export const copyText = (text: string) => {
  navigator.clipboard
    .writeText(text)
    .catch((err: unknown) =>
      console.error('Failed to copy text to clipboard:', err)
    );
}

Resources:

Example usage:

import { copyText } from './copy-text.util';

// 1) Simple text copy
copyText('Hello, clipboard!');

// 2) In a React component
function InviteButton() {
  const inviteLink = 'https://example.com/invite';
  return (
    <button onClick={() => copyText(inviteLink)}>
      Copy Invite Link
    </button>
  );
}