useDropZone
Create an zone where files can be dropped
useDropZone turns a DOM element into a file drop target by handling the dragenter, dragover, dragleave, and drop events. It returns a boolean indicating whether a file is currently being dragged over the zone. When files are dropped, the provided callback receives an array of File objects (or null if no files were dropped).
When to Use
- Building file upload interfaces where users drag and drop files from their desktop
- Creating media galleries or document managers with drag-and-drop support
- Implementing drag-and-drop zones in form builders or CMS editors
Notes
- Visual feedback: Use the returned
isOverboolean to highlight the drop zone (e.g., change border color or background) when a file is dragged over it. - Cleanup: All drag-related event listeners are removed automatically when the component unmounts.
- See also
useDraggablefor making elements draggable within the page (element repositioning vs. file drops).
Usage
Live Editor
function Demo() { const ref = useRef<HTMLDivElement>(null); const isOver = useDropZone(ref, (_files) => {}); return ( <div> <p>Drop files into dropZone</p> {/* <img src={logo} alt="" /> */} <div ref={ref} style={{ minHeight: 200, display: "flex", alignItems: "center", justifyContent: "center", marginTop: "1.5rem", background: "rgba(156,163,175,0.1)", }} > <div> isOverDropZone: {JSON.stringify(isOver)}</div> </div> </div> ); };
Result
API
useDropZone
Returns
boolean: Whether the file is on the zone
Arguments
| Argument | Description | Type | DefaultValue |
|---|---|---|---|
| target | target element | BasicTarget<EventTarget> (Required) | - |
| onDrop | drop callback | ((files: File[] | null) => void) | undefined | - |
BasicTarget
export type BasicTarget<T extends TargetType = Element> = (() => TargetValue<T>) | TargetValue<T> | MutableRefObject<TargetValue<T>>;
TargetValue
type TargetValue<T> = T | undefined | null;
TargetType
type TargetType = HTMLElement | Element | Window | Document | EventTarget;