React Copy to Clipboard

5.1.1 · active · verified Sun Apr 19

react-copy-to-clipboard is a React component that simplifies the process of copying text to the user's clipboard. It acts as a wrapper around the core `copy-to-clipboard` library, offering a declarative API for use within React applications. The component intelligently attempts to copy text using `document.execCommand('copy')`, falls back to the IE-specific `clipboardData` interface, and, if all else fails, provides a prompt for manual copying. The current stable version is 5.1.1. Releases are generally driven by dependency updates, bug fixes, or new React version compatibility. Its key differentiators include its simple, single-child wrapper pattern and its robust, multi-strategy approach to clipboard access, ensuring broad browser compatibility and reliability.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates a basic React functional component using `CopyToClipboard` to copy text from an input field, showing visual feedback upon successful copy.

import React from 'react';
import ReactDOM from 'react-dom';
import { CopyToClipboard } from 'react-copy-to-clipboard';

function App() {
  const [value, setValue] = React.useState('');
  const [copied, setCopied] = React.useState(false);

  return (
    <div>
      <input
        value={value}
        onChange={({ target: { value } }) => {
          setValue(value);
          setCopied(false);
        }}
        placeholder="Enter text to copy"
        style={{ padding: '8px', border: '1px solid #ccc' }}
      />

      <CopyToClipboard text={value} onCopy={() => setCopied(true)}>
        <button style={{ marginLeft: '10px', padding: '8px 15px', cursor: 'pointer' }}>
          Copy to clipboard
        </button>
      </CopyToClipboard>

      {copied ? <span style={{ color: 'green', marginLeft: '10px' }}>Copied!</span> : null}
    </div>
  );
}

const appRoot = document.createElement('div');
document.body.appendChild(appRoot);
ReactDOM.render(<App />, appRoot);

view raw JSON →