Skip to content
Browse documentation

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

Used forForms with attachmentsSettings pagesMedia and document librariesImport steps

Install with the shadcn CLI

$ npx shadcn@latest add @hairline/drop-zone

Older shadcn CLI, or a network that blocks ui.shadcn.com? Install by URL: shadcn add https://hairlineui.com/r/drop-zone.json. More

Templates

Need the whole page?

65 Next.js landing pages, each designed from scratch. Try any of them live; one is $39, all of them $159, and 8 are free.

Where it’s used

  • 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.

What it handles for you

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.

Instead of wiring upa hidden file inputdrag and drop handlersfile validationupload progress rowscancel and retry logic
  1. Drop, browse or paste

    The whole area opens the file picker, files can be dragged onto it, and pasted files are added.

  2. It validates the files

    Type, size, count and duplicates are checked. Rejections are listed under the area, and onFilesRejected tells your code why.

  3. Progress in each row

    Name, size, a rolling percent and a ring, with the row’s bottom hairline filling as it uploads.

  4. Cancel and Retry

    Cancel aborts the upload, late results from a cancelled attempt are ignored, and a failed file offers Retry.

  5. Selection-only mode

    Without onUpload the files are marked Ready and handed to your form through onFilesChange.

  6. 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.

Overview

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.

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.

Usage

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 });  }}/>

Depends on lucide-react, installed for you by the CLI along with the keyframes it needs.

Works with

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.

example.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

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= true
boolean
false accepts one file and replaces the previous valid selection. An invalid replacement keeps the current file.
title= "Drop files here"
string
Heading inside the drop area.
hint
string
Custom file requirements below the heading. Defaults to the accepted types and configured limits.
disabled= false
boolean
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.

Accessibility and motion

  • 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.

Requirements

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

The CLI also installs Text morph, Number roll.

Source

'use client';import * as React from 'react';import { ArrowUp, CircleAlert, X } from 'lucide-react';import { DropZoneFileRow } from './drop-zone-file-row';import type { DropZoneProps } from './drop-zone-types';import { selectionHint } from './drop-zone-utils';import { useDropZone } from './use-drop-zone';import { TextMorph } from './text-morph';import { INTERACTION_FOCUS } from './ui-interaction-motion';export type { DropZoneStatus, DropZoneFile, DropZoneUpload, DropZoneRejection, DropZoneHandle, DropZoneProps } from './drop-zone-types';export { formatBytes } from './drop-zone-utils';const carriesFiles = (data: DataTransfer) => Array.from(data.types).includes('Files');export function DropZone({  onUpload, onFilesChange, onFilesRejected, accept, maxSize, maxFiles, multiple = true,  title = 'Drop files here', hint, disabled = false, ref, className = '', onPaste, ...props}: DropZoneProps) {  const input = React.useRef<HTMLInputElement>(null);  const area = React.useRef<HTMLButtonElement>(null);  const depth = React.useRef(0);  const [dragging, setDragging] = React.useState(false);  const id = React.useId();  const { rows, rejections, announcement, add, remove, retry, dismissRejections } = useDropZone({    onUpload, onFilesChange, onFilesRejected, accept, maxSize, maxFiles, multiple, disabled,  });  const description = hint ?? selectionHint(accept, maxSize, multiple ? maxFiles : 1);  const cancel = React.useCallback(() => { depth.current = 0; setDragging(false); }, []);  const browse = React.useCallback(() => { if (!disabled) input.current?.click(); }, [disabled]);  const contains = React.useCallback((x: number, y: number) => {    const rect = area.current?.getBoundingClientRect();    return !!rect && rect.width > 0 && rect.height > 0 && x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;  }, []);  const [seenDisabled, setSeenDisabled] = React.useState(disabled);  if (disabled !== seenDisabled) {    setSeenDisabled(disabled);    if (disabled && dragging) setDragging(false);  }  React.useEffect(() => { if (disabled) depth.current = 0; }, [disabled]);  React.useImperativeHandle(ref, () => ({    browse, cancel,    drag: (x, y) => {      const inside = !disabled && contains(x, y);      setDragging(inside);      return inside;    },    drop: (files, at) => {      cancel();      if (!at || contains(at.x, at.y)) add(files);    },  }), [browse, cancel, disabled, contains, add]);  return (    <div      {...props}      className={`@container relative w-full min-w-0 text-foreground ${className}`}      onPaste={(event) => {        onPaste?.(event);        if (event.defaultPrevented || disabled) return;        const files = Array.from(event.clipboardData.files);        if (files.length) { event.preventDefault(); cancel(); add(files); }      }}    >      <button        ref={area}        type="button"        disabled={disabled}        onClick={browse}        aria-label={`Browse ${multiple ? 'files' : 'file'}`}        aria-describedby={`${id}-title ${id}-hint`}        data-drop-zone=""        data-dragging={dragging || undefined}        aria-disabled={disabled || undefined}        onDragEnter={(event) => {          if (!carriesFiles(event.dataTransfer)) return;          event.preventDefault();          if (!disabled) { depth.current++; setDragging(true); }        }}        onDragOver={(event) => {          if (!carriesFiles(event.dataTransfer)) return;          event.preventDefault();          event.dataTransfer.dropEffect = disabled ? 'none' : 'copy';          if (!disabled) setDragging(true);        }}        onDragLeave={(event) => {          event.preventDefault();          depth.current = Math.max(0, depth.current - 1);          if (!depth.current) setDragging(false);        }}        onDrop={(event) => {          event.preventDefault();          cancel();          add(Array.from(event.dataTransfer.files));        }}        onDragEnd={cancel}        className={`relative flex min-h-[152px] w-full cursor-pointer flex-col items-center justify-center gap-3 rounded-[18px] border px-5 py-5 text-center transition-colors duration-200 disabled:cursor-default disabled:opacity-55 motion-reduce:transition-none @md:min-h-[176px] ${INTERACTION_FOCUS} ${          dragging ? 'border-primary bg-primary/5' : 'border-border bg-muted/45'        }`}      >        <span className={`relative flex size-9 shrink-0 items-center justify-center rounded-full border bg-background transition-colors duration-200 motion-reduce:transition-none ${dragging ? 'border-primary/30 text-primary' : 'border-border text-muted-foreground'}`}>          <ArrowUp className="size-4" strokeWidth={1.75} aria-hidden="true" />        </span>        <span className="relative flex max-w-full flex-col items-center gap-1">          <span id={`${id}-title`} className="text-[13.5px] font-medium tracking-[-0.01em]">            <TextMorph>{dragging ? 'Release to add' : title}</TextMorph>          </span>          <span id={`${id}-hint`} className="text-balance text-[12px] leading-relaxed text-muted-foreground">            <span className="whitespace-nowrap"><span className="text-foreground underline decoration-border underline-offset-[3px]">Browse</span> or paste ·</span> {description}          </span>        </span>      </button>      <input        ref={input} type="file" hidden disabled={disabled} multiple={multiple} accept={accept}        onChange={(event) => {          const files = Array.from(event.currentTarget.files ?? []);          event.currentTarget.value = '';          cancel();          add(files);        }}      />      {rejections.length > 0 && (        <div role="alert" className="mt-2 flex items-start gap-2 text-red-600 dark:text-red-400">          <CircleAlert className="mt-2 size-3.5 shrink-0" aria-hidden="true" />          <div className="min-w-0 flex-1 py-1.5 text-[12px] leading-relaxed [overflow-wrap:anywhere]">            {rejections.slice(0, 3).map((rejection, index) => (              <p key={index} className="break-words"><span className="font-medium">{rejection.file.name}</span> — {rejection.reason}</p>            ))}            {rejections.length > 3 && <p className="mt-1">{rejections.length - 3} more files skipped.</p>}          </div>          <button type="button" aria-label="Dismiss file errors" onClick={dismissRejections} className={`flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-full hover:bg-muted ${INTERACTION_FOCUS}`}>            <X className="size-3.5" aria-hidden="true" />          </button>        </div>      )}      {rows.length > 0 && (        <ul aria-label="Files" className="mt-3 min-w-0">          {rows.map((row) => <DropZoneFileRow key={row.id} row={row} disabled={disabled} onRemove={() => remove(row.id)} onRetry={() => retry(row.id)} />)}        </ul>      )}      <p role="status" aria-live="polite" aria-atomic="true" className="sr-only">{announcement}</p>    </div>  );}

Registry item: /r/drop-zone.json