Clipboard API: Copy and Paste in React
Implement copy-to-clipboard buttons using the modern Clipboard API and fall back gracefully for older browsers.
Clipboard API: Copy and Paste in React is a free React Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the React Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Writing to the Clipboard
navigator.clipboard.writeText(text) writes a string to the system clipboard and returns a Promise. It is the modern replacement for the legacy execCommand approach. Always await the Promise and handle the potential rejection, for example when the user denies clipboard access.
Reading from the Clipboard
navigator.clipboard.readText() reads the current clipboard content as a string and also returns a Promise. Reading requires the clipboard-read permission, which the browser prompts the user to grant. In practice, clipboard read is used less often than write in typical React applications.
Clipboard Write Requires a User Gesture
Browsers enforce that clipboard.writeText can only be called within a user gesture handler, such as a click or keydown event. Calling it inside a useEffect or asynchronously after the gesture will throw a security error. Always trigger the write directly from an onClick handler.
Copy-to-Clipboard UI Pattern
The standard pattern is: user clicks a copy button, your handler calls navigator.clipboard.writeText(value), on success you set a copied state to true, and the button temporarily shows a checkmark or "Copied!" label. After a short delay the button returns to its normal state.
Building useCopyToClipboard Hook
Encapsulate the logic in a useCopyToClipboard hook that returns a tuple: [copied, copyFn]. The copied boolean drives the UI feedback, and copyFn accepts the text to copy. The hook handles the async write and any error internally so components stay simple.
Resetting the Copied State
Inside the hook, after a successful copy set setCopied(true) and schedule a reset with setTimeout(() => setCopied(false), 2000). Store the timeout ID and clear it in a useEffect cleanup to prevent state updates after unmount. This avoids the "cannot update state on an unmounted component" warning.
Legacy Fallback with execCommand
Older browsers and non-HTTPS pages do not support the Clipboard API. The legacy fallback creates a temporary textarea, sets its value, appends it to the body, calls document.execCommand('copy'), and removes the element. This approach is synchronous and works everywhere, though it is deprecated.
Detecting Clipboard API Availability
Before using the Clipboard API, check: navigator.clipboard && typeof navigator.clipboard.writeText === 'function'. If unavailable, fall back to the legacy execCommand approach. This defensive check prevents runtime errors in environments where the API is not supported.
Clipboard Read Permission
Clipboard read requires user permission via the Permissions API. You can query the current state: navigator.permissions.query({ name: 'clipboard-read' }) returns a PermissionStatus with a state of granted, denied, or prompt. The browser will prompt automatically when you call readText().
HTTPS Requirement
The Clipboard API is only available in secure contexts (HTTPS or localhost). On HTTP pages, navigator.clipboard is undefined. This is a security restriction because clipboard content can be sensitive. Always check the availability of the API before referencing its methods to avoid null reference errors.
Testing Clipboard in jsdom
jsdom (used by Jest) does not implement the Clipboard API. Mock it in your test setup: Object.assign(navigator, { clipboard: { writeText: jest.fn().mockResolvedValue(undefined) } }). This lets you test that your component calls writeText with the correct argument without a real browser environment.
Clipboard Write Requirements
When can navigator.clipboard.writeText() be safely called in the browser?
Lesson Recap: Clipboard API in React
Use navigator.clipboard.writeText() inside a click handler to copy text. Build a useCopyToClipboard hook returning [copied, copyFn] with a timed reset. Always check API availability, provide an execCommand fallback for older browsers, and mock navigator.clipboard in Jest tests.
Frequently asked questions
Is the “Clipboard API: Copy and Paste in React” lesson free?
Yes — the full text of “Clipboard API: Copy and Paste in React” is free to read here on the web, and the React Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the React Academy course, upgrade to CoddyKit PRO.
What will I learn in “Clipboard API: Copy and Paste in React”?
Implement copy-to-clipboard buttons using the modern Clipboard API and fall back gracefully for older browsers. You practise React Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start React Academy?
No prior experience is required. React Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Clipboard API: Copy and Paste in React” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this React Academy lesson?
Yes. Every React Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Clipboard API: Copy and Paste in React
- Geolocation API in React Components
- Notifications API and Permission Handling
- IntersectionObserver for Scroll-Triggered Effects