dnd-supports
v1.1.4
Published
Tiny dependency-free HTML5 drag-and-drop file helper.
Maintainers
Readme
dnd-supports
Tiny, dependency-free drag-and-drop file support for browsers.
Adds HTML5 drag-and-drop file support to any HTMLElement with a single function.
- 🚀 Zero dependencies for vanilla use
- 📦 Tiny (~1 kB minified)
- 🔥 TypeScript ready
- 🧹 Automatic cleanup
- 🎯 Optional CSS class handling
Installation
npm install dnd-supportsor
<script type="module">
import { dndSupport } from "https://cdn.jsdelivr.net/npm/dnd-supports/+esm";
// or
import { dndSupport } from "https://esm.sh/dnd-supports";
</script>Usage
import { dndSupport } from "dnd-supports";
const dispose = dndSupport(
"#drop-area",
files => {
console.log(files);
},
{
dropTargetClasses: "drag-over"
}
);
// later...
dispose();The target can be an HTMLElement or a CSS selector. A selector uses the
first matching element and does not create or insert any DOM elements.
React
React support is available from dnd-supports/react. It requires React 18 or
later, which should be installed by the consuming application.
useFileDrop()
Use the hook to attach support to an existing element or a CSS selector. It does not create or render an element.
import { useFileDrop } from "dnd-supports/react";
export const UploadArea = () => {
useFileDrop(
"#drop-area",
files => {
console.log(files);
},
{
dropTargetClasses: "drag-over"
}
);
return <div id="drop-area">Drop files here</div>;
};FileDropSupport
FileDropSupport is a convenience component for attaching support to an
existing target. It renders no DOM element.
import { FileDropSupport } from "dnd-supports/react";
export const UploadArea = () => (
<>
<FileDropSupport
target="#drop-area"
onDrop={files => {
console.log(files);
}}
dropTargetClasses="drag-over"
/>
<div id="drop-area">Drop files here</div>
</>
);Options
| Option | Type | Description |
|--------|------|-------------|
| target | HTMLElement \| string | Drop target element or CSS selector. Selectors use the first matching element. |
| dropTargetClasses | string | CSS class names applied while dragging over the target. |
| verbose | true | Enables console logging. |
Callback
(files: readonly File[]) => voidFiles are provided as a readonly array.
API
dndSupport()
const dispose = dndSupport(
target,
files => {},
options
);target accepts an HTMLElement or CSS selector. Returns a cleanup function
that removes all event listeners.
License
MIT
