All hooks / Events and input
usePasteFiles
Calls onFiles when the user pastes files, such as a screenshot, while focus is inside an element. Returns a callback ref for the element, e.g. a chat input or its wrapper.
Only pastes that contain matching files are taken: their default is prevented so the file name isn't pasted as text. Plain text pastes are left alone.
Import
import { usePasteFiles } from '@vincent.ri/react-tils'
// or only this hook
import { usePasteFiles } from '@vincent.ri/react-tils/usePasteFiles'Usage
const ref = usePasteFiles((files) => attach(files), { accept: 'image/*' })
return <textarea ref={ref} placeholder="Message, or paste a screenshot" />Live demo
Copy a screenshot, click the box, and paste. Text pastes normally.
When to use it
Pasting images into a chat, a comment box, an editor, or an upload area.
When not to
You want drag and drop; use useFileDrop (they work well together). Keep an <input type="file"> too, for users who don't paste.
API
function usePasteFiles<T extends HTMLElement = HTMLElement>(onFiles: (files: File[], event: ClipboardEvent) => void, options?: PasteFilesOptions): (element: T | null) => void| Parameter | Description |
|---|---|
onFiles | Called with the pasted files and the event. Can change every render. |
options | enabled, accept. Optional. |
Returns A callback ref. Pass it to the element that contains the focused input.
Types
export type PasteFilesOptions = {
/** Listen while `true`. Default `true`. */
enabled?: boolean;
/** Which files to take, like an `<input type="file">` `accept`: `'image/*'`, `'application/pdf'`, `'.csv'`. Default: all files. */
accept?: string;
};Browser support
| Uses | Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS |
|---|---|---|---|---|---|---|
| paste eventWidely available | 1+ | 12+ | 22+ | 3+ | 18+ | 3+ |
First version with support, from MDN's compatibility data (web-features 3.42.0, @mdn/browser-compat-data 8.1.5).
Coming from another library?
Other libraries call this usePaste, useClipboardFiles.