React Reference ยท Props and Attributes
React clipboard events (onCopy, onCut and onPaste)
Reference for React clipboard events: onCopy, onCut and onPaste, reading and changing clipboardData, and how they differ from the async Clipboard API.
Three props react to the user's clipboard actions: onCopy, onCut and onPaste. They run when the user presses the keyboard shortcut or picks the command from a menu, inside the same user gesture. The event carries a clipboardData object. In onCopy and onCut you can replace what goes on the clipboard; in onPaste you can read what is about to be pasted and change what happens.
These events are separate from navigator.clipboard, the asynchronous Clipboard API. The events are tied to a user action and need no permission. The API can be called from any code but requires a secure context, focus, and often a permission prompt. Inside the sandboxed preview used on this site, navigator.clipboard is blocked, which makes the events the practical choice for the examples here.
<input onPaste={(e) => { e.preventDefault(); const text = e.clipboardData.getData('text'); // use text... }} />
Try it
Syntax
<element onCopy={(event: React.ClipboardEvent) => void} onCut={(event: React.ClipboardEvent) => void} onPaste={(event: React.ClipboardEvent) => void} />
| Name | Description |
|---|---|
event.clipboardData |
A DataTransfer object. getData(type) reads, setData(type, text) writes, types lists formats, files holds pasted files such as screenshots. |
event.preventDefault() |
In onCopy and onCut it tells the browser to use the data you set instead of the selection. In onPaste it stops the browser inserting the text. |
Returns: nothing.
Edge cases: reading clipboardData works only while the handler runs. Copying it into state and reading the DataTransfer later gives empty values. Read first, then store the string.
Usage notes
- Common types:
'text/plain'and'text/html'. Browsers may offer several; ask for the one you need and ignore the rest. onCutalso edits. If you callpreventDefault()inonCut, the selected text is not removed from the field. Remove it yourself.- Pasted files. Images pasted from a screenshot tool appear in
e.clipboardData.files(oritems). Read them withFileReaderorURL.createObjectURL. - Controlled inputs. After you intercept a paste, you update state yourself, as shown above. If you also care about the caret, you need to set the selection range after the update.
- Bubbling. The events bubble, so a handler on a form catches copies and pastes from every field in it.
- Do not trap users. Disabling paste in password or confirmation fields is widely considered hostile, and password managers rely on it.
- Security. Pasted HTML is untrusted. Never insert it with
dangerouslySetInnerHTMLwithout sanitizing it. - Copy buttons (a "Copy" button next to a code sample) need
navigator.clipboard.writeText()in a real page, because there is no copy event on a button click. Show it as read-only code where the API is blocked.