# Drop zone

> A considered file uploader. Clear actions, quiet progress and useful feedback.

The same compact layout as Drop zone · Membrane, with a steady border and files that appear directly in their rows. The whole upload area opens the file picker; Browse or paste stays inline below the label. Files sit on simple hairlines, with size, progress and actions aligned on the right. Errors use the full width below their file row so messages stay readable on phones. The progress ring, drawn check and quiet label changes remain. The elastic border, proximity capture, following arrow and flying files are removed. Use it as a file picker in a form, or connect onUpload to your own storage.

## Install

```bash
npx shadcn@latest add @hairline/drop-zone
```

Needs React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

- npm: `lucide-react`
- Hairline UI components it needs (the CLI installs them too): `text-morph`, `number-roll`
- Docs and live preview: https://hairlineui.com/ui/drop-zone
- Registry item (source): https://hairlineui.com/r/drop-zone.json

## Usage

```tsx
import { DropZone } from "@/components/drop-zone";

<DropZone
  accept="image/*,.pdf"
  maxSize={10_000_000}
  maxFiles={6}
  onFilesChange={setFiles}
  onUpload={async (file, { progress, signal }) => {
    await uploadFile(file, { onProgress: progress, signal });
  }}
/>
```

## Connect your own storage

onUpload runs once per accepted file. Report progress from 0 to 1, honour the abort signal and throw an Error to show a retryable failure. This example requests a presigned URL from your API and sends the file with XMLHttpRequest for upload progress. Omit onUpload to use selection only.

```tsx
"use client";
import { DropZone } from "@/components/drop-zone";

export function AssetUpload({ projectId }: { projectId: string }) {
  return (
    <DropZone
      accept="image/*,.pdf"
      maxSize={10_000_000}
      maxFiles={6}
      onUpload={async (file, { progress, signal }) => {
        const res = await fetch("/api/uploads", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ projectId, name: file.name, type: file.type }),
          signal,
        });
        if (!res.ok) throw new Error("Could not prepare the upload.");
        const { url } = await res.json();
        await new Promise<void>((resolve, reject) => {
          const xhr = new XMLHttpRequest();
          const abort = () => xhr.abort();
          const cleanup = () => signal.removeEventListener("abort", abort);
          xhr.open("PUT", url);
          xhr.setRequestHeader("Content-Type", file.type || "application/octet-stream");
          xhr.upload.onprogress = (e) => {
            if (e.lengthComputable) progress(e.loaded / e.total);
          };
          xhr.onload = () => {
            cleanup();
            if (xhr.status >= 200 && xhr.status < 300) resolve();
            else reject(new Error("Upload failed. Please try again."));
          };
          xhr.onerror = () => { cleanup(); reject(new Error("Connection lost.")); };
          xhr.onabort = () => { cleanup(); reject(new DOMException("Cancelled", "AbortError")); };
          if (signal.aborted) {
            reject(new DOMException("Cancelled", "AbortError"));
            return;
          }
          signal.addEventListener("abort", abort, { once: true });
          xhr.send(file);
        });
      }}
    />
  );
}
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `onUpload` | `DropZoneUpload` | – | Uploads a file with { progress, signal }. Resolve to mark Uploaded; throw to show Retry. Without this callback, files stay Ready. |
| `onFilesChange` | `(files: File[]) => void` | – | Current selection after adding, replacing or removing files. Progress updates do not trigger this callback. |
| `onFilesRejected` | `(rejections: DropZoneRejection[]) => void` | – | Rejected files with a reason and a type, size, count or duplicate code, for your own feedback or logging. |
| `accept` | `string` | – | Native file-input syntax: MIME types, wildcards or extensions, e.g. "image/*,.pdf". |
| `maxSize` | `number` | – | Maximum size per file in bytes. The limit appears in the default hint. |
| `maxFiles` | `number` | – | Maximum number of files in the selection. Excess files are skipped; valid files still get added. |
| `multiple` | `boolean` | `true` | false accepts one file and replaces the previous valid selection. An invalid replacement keeps the current file. |
| `title` | `string` | `"Drop files here"` | Heading inside the drop area. |
| `hint` | `string` | – | Custom file requirements below the heading. Defaults to the accepted types and configured limits. |
| `disabled` | `boolean` | `false` | Disables browsing, adding, removing and retrying. In-flight uploads continue. |
| `ref` | `Ref<DropZoneHandle>` | – | browse(), drop(files, at?), drag(x, y, types?) and cancel() for app-driven file selection. Coordinates are accepted only inside the drop area. |
| `className` | `string` | – | Styles the root. Standard div attributes and style are also forwarded. |

## States

- **idle**: The original 18px upload surface, circular arrow and inline Browse or paste prompt. The whole surface is a button. Its height starts at 152px and grows for wider containers or longer hints.
- **drag over**: Only the drop area responds: the border and background take a restrained accent, and the label morphs to "Release to add". Its shape stays fixed.
- **ready**: Without onUpload, files are marked Ready and passed to onFilesChange for use in a form. They are never reported as uploaded.
- **uploading**: A compact hairline row shows the file name, size, rolling percentage and a progress ring. Its bottom hairline fills with progress. Cancel removes the file and aborts its upload.
- **complete**: The progress ring gives way to the original small blue drawn check when your upload callback resolves. Completion is also announced as Uploaded.
- **error**: Failed and Retry stay on the compact row, while the message uses a separate full-width line underneath. Invalid types, oversized files, duplicates and excess files are listed below the drop area until dismissed or another selection is made.

## What it handles

A file uploader needs more than a box: limits, progress, cancelling, retrying and clear errors. This is the quiet version, for forms and settings where it should not draw attention.

- **Drop, browse or paste**: The whole area opens the file picker, files can be dragged onto it, and pasted files are added.
- **It validates the files**: Type, size, count and duplicates are checked. Rejections are listed under the area, and onFilesRejected tells your code why.
- **Progress in each row**: Name, size, a rolling percent and a ring, with the row’s bottom hairline filling as it uploads.
- **Cancel and Retry**: Cancel aborts the upload, late results from a cancelled attempt are ignored, and a failed file offers Retry.
- **Selection-only mode**: Without onUpload the files are marked Ready and handed to your form through onFilesChange.
- **Several on one page**: Drag listeners belong to the drop area and there are no window listeners, so uploaders do not interfere with each other.

## Replaces

a hidden file input, drag and drop handlers, file validation, upload progress rows, cancel and retry logic

## Where it fits

- **Forms with attachments**: Support requests and applications where people add files.
- **Settings pages**: Upload a logo, a certificate or a document in an account page.
- **Media and document libraries**: Add several files at once and see each one finish.
- **Import steps**: The upload step before a file is processed or imported.

## Notes

- A native button provides keyboard browsing. Paste files while focus is inside the component. File results are announced through live regions, and each progress bar is labelled with its file name.
- Drag listeners belong to the drop area, so multiple uploaders can sit on a page independently. No window listeners, proximity targets or perpetual animation loop.
- Remove, replacement and unmount abort the relevant uploads. Late progress or promise results from a cancelled attempt are ignored. Retry starts a fresh attempt.
- Duplicates are compared by file name, size, MIME type and last-modified time. Remove a file to select it again.
- All supporting files ship together, along with Text morph and Number roll for the original quiet label and progress feedback. No animation library or additional stylesheet keyframes.
- Reduced motion keeps labels, numbers and status icons in place. Feedback remains visible as text, a check and progress.

License: MIT (https://hairlineui.com/license#components)
