Back to Hooks

useCopyToClipboard

useCopyToClipboard.tsx

useCopyToClipboard

UTILITY

// Simplifies copying text/content directly to clipboard

Quick Usage

const { copy, copied, history } = useCopyToClipboard({ trackHistory: true });

Features

Clipboard API
History Tracking
Fallback Support
Error Handling

When to Use

Perfect for copy-to-clipboard functionality, sharing features, or text utilities requiring clipboard access.

Interactive Example

Complete Example

import { useCopyToClipboard } from '@usegrand/react-hokss';

function CopyButton({ text }) {
  const { copy, copied, error, history } = useCopyToClipboard({ 
    trackHistory: true, 
    maxHistorySize: 5 
  });

  return (
    <div>
      <button onClick={() => copy(text)}>
        {copied ? 'Copied!' : 'Copy'}
      </button>
      {error && <p>Error: {error}</p>}
      {history.length > 0 && (
        <ul>
          {history.map((item, index) => (
            <li key={index}>{item}</li>
          ))}
        </ul>
      )}
    </div>
  );
}

API Reference

Parameters

optionsCopyToClipboardOptions

Configuration options for clipboard functionality

options.trackHistoryboolean

Whether to track clipboard history (default: false)

options.maxHistorySizenumber

Maximum number of items to keep in history (default: 10)

Returns

CopyToClipboardResult

Object containing copy function and state

copy

Function to copy text to clipboard

copied

Boolean indicating if last copy was successful

error

Error message if copy operation failed

history

Array of previously copied items

clearHistory

Function to clear clipboard history