Overview

A complete upload surface. Dragging a file anywhere on the page arms the zone, and over it the dashed border marches, the sheet stack fans out and lifts, and the label tells you how many files you're about to add. Drops that miss the zone no longer navigate the tab to the file. Files are validated one by one (type, size, count) so one bad file doesn't sink the batch; rejections are listed with reasons. Accepted files get a row with an image preview or type badge, size, a progress bar and a status, plus cancel, remove and retry. Paste works when the zone is focused.


Installation

Use the CLI to install the component automatically:

$ pnpm dlx shadcn@latest add https://ui.sanjid.in/r/file-dropzone.json

Install dependencies:

$ pnpm add motion lucide-react

Add the utility function for class merging:

lib/utils.ts
tsx
import { ClassValue, clsx } from "clsx";import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {  return twMerge(clsx(inputs));}

Copy the component code into your project:

components/ui/file-dropzone.tsx
tsx
"use client";
import React, { useCallback, useEffect, useId, useRef, useState } from "react";import {  AnimatePresence,  motion,  useAnimate,  useReducedMotion,} from "motion/react";import { Check, FileText, RotateCcw, X } from "lucide-react";import { cn } from "@/lib/utils";
export type DropzoneFileStatus = "queued" | "uploading" | "done" | "error";
export type DropzoneFile = {  id: string;  file: File;  status: DropzoneFileStatus;  progress: number;  preview?: string;  error?: string;};
export type FileDropzoneProps = {  /** Fires with each batch of accepted files. */  onFiles?: (files: File[]) => void;  /**   * Optional uploader. Call `progress(0–1)` as bytes go out; throw to fail.   * The signal aborts when the user removes the file mid-upload.   */  upload?: (file: File, progress: (p: number) => void, signal: AbortSignal) => Promise<void>;  onRemove?: (file: File) => void;  accept?: string;  multiple?: boolean;  /** Per-file size limit in bytes. */  maxSize?: number;  /** Total files the list will hold. */  maxFiles?: number;  disabled?: boolean;  /** Render the built-in file list under the zone. */  showList?: boolean;  className?: string;  label?: string;  hint?: string;};
type ZoneState = "idle" | "armed" | "over" | "reject";
const EASE_OUT = [0.23, 1, 0.32, 1] as const;const SPRING = { type: "spring" as const, bounce: 0.2, duration: 0.45 };
/* ── Helpers ─────────────────────────────────────────────── */
function formatBytes(bytes: number) {  if (bytes < 1024) return `${bytes} B`;  const units = ["KB", "MB", "GB"];  let n = bytes / 1024;  let i = 0;  while (n >= 1024 && i < units.length - 1) {    n /= 1024;    i++;  }  return `${n < 10 ? n.toFixed(1) : Math.round(n)} ${units[i]}`;}
function acceptList(accept?: string) {  return accept ? accept.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean) : [];}
function matchesAccept(name: string, type: string, rules: string[]) {  if (!rules.length) return true;  const lower = name.toLowerCase();  return rules.some((r) => {    if (r.startsWith(".")) return lower.endsWith(r);    if (r.endsWith("/*")) return type.startsWith(r.slice(0, -1));    return type === r;  });}
/** During a drag only MIME types are visible; extensions can't be checked yet. */function dragLooksRejected(items: DataTransferItemList, rules: string[]) {  const mimeRules = rules.filter((r) => !r.startsWith("."));  if (!mimeRules.length || rules.length !== mimeRules.length) return false;  return Array.from(items).some(    (it) => it.kind === "file" && it.type && !matchesAccept("", it.type, mimeRules),  );}
function hasFiles(e: DragEvent | React.DragEvent) {  return Array.from(e.dataTransfer?.types ?? []).includes("Files");}
function splitName(name: string) {  const dot = name.lastIndexOf(".");  return dot > 0 ? [name.slice(0, dot), name.slice(dot)] : [name, ""];}
let uid = 0;const nextId = () => `f${Date.now().toString(36)}${(uid++).toString(36)}`;
/* ── Component ───────────────────────────────────────────── */
export function FileDropzone({  onFiles,  upload,  onRemove,  accept,  multiple = true,  maxSize,  maxFiles,  disabled,  showList = true,  className,  label = "Drop files here",  hint = "or click to browse",}: FileDropzoneProps) {  const reduce = useReducedMotion();  const baseId = useId();  const inputRef = useRef<HTMLInputElement>(null);  const [zoneRef, animateZone] = useAnimate<HTMLDivElement>();  const [state, setState] = useState<ZoneState>("idle");  const [dragCount, setDragCount] = useState(0);  const [items, setItems] = useState<DropzoneFile[]>([]);  const [rejections, setRejections] = useState<string[]>([]);  const itemsRef = useRef(items);  itemsRef.current = items;  const controllers = useRef(new Map<string, AbortController>());  const zoneDepth = useRef(0);
  const rules = acceptList(accept);  const limit = multiple ? (maxFiles ?? Infinity) : 1;
  /* Window-level drag: arm the zone when a file enters the page, and stop a     drop that misses the zone from navigating the tab to the file. */  useEffect(() => {    if (disabled) return;    let depth = 0;    const enter = (e: DragEvent) => {      if (!hasFiles(e)) return;      depth++;      setState((s) => (s === "idle" ? "armed" : s));    };    const leave = (e: DragEvent) => {      if (!hasFiles(e)) return;      depth = Math.max(0, depth - 1);      if (depth === 0) setState("idle");    };    const over = (e: DragEvent) => {      if (!hasFiles(e)) return;      e.preventDefault();      if (e.dataTransfer && zoneDepth.current === 0) e.dataTransfer.dropEffect = "none";    };    const drop = (e: DragEvent) => {      depth = 0;      if (!hasFiles(e)) return;      e.preventDefault();      setState("idle");    };    window.addEventListener("dragenter", enter);    window.addEventListener("dragleave", leave);    window.addEventListener("dragover", over);    window.addEventListener("drop", drop);    return () => {      window.removeEventListener("dragenter", enter);      window.removeEventListener("dragleave", leave);      window.removeEventListener("dragover", over);      window.removeEventListener("drop", drop);    };  }, [disabled]);
  // Revoke previews and abort uploads on unmount.  useEffect(    () => () => {      itemsRef.current.forEach((it) => it.preview && URL.revokeObjectURL(it.preview));      controllers.current.forEach((c) => c.abort());    },    [],  );
  const patch = (id: string, next: Partial<DropzoneFile>) =>    setItems((list) => list.map((it) => (it.id === id ? { ...it, ...next } : it)));
  const runUpload = useCallback(    async (item: DropzoneFile) => {      if (!upload) return;      const controller = new AbortController();      controllers.current.set(item.id, controller);      patch(item.id, { status: "uploading", progress: 0, error: undefined });      try {        await upload(          item.file,          (p) => patch(item.id, { progress: Math.min(1, Math.max(0, p)) }),          controller.signal,        );        if (!controller.signal.aborted) patch(item.id, { status: "done", progress: 1 });      } catch (err) {        if (controller.signal.aborted) return;        patch(item.id, {          status: "error",          error: err instanceof Error && err.message ? err.message : "Upload failed",        });      } finally {        controllers.current.delete(item.id);      }    },    [upload],  );
  const shake = () => {    if (reduce || !zoneRef.current) return;    animateZone(zoneRef.current, { x: [0, -8, 7, -5, 3, 0] }, { duration: 0.4, ease: "easeOut" });  };
  const addFiles = useCallback(    (list: FileList | File[] | null) => {      if (!list || disabled) return;      const incoming = Array.from(list);      if (!incoming.length) return;
      const reasons: string[] = [];      const accepted: File[] = [];      let room = limit - itemsRef.current.length;
      for (const file of incoming) {        if (!matchesAccept(file.name, file.type, rules)) {          reasons.push(`${file.name} isn't an accepted type`);        } else if (maxSize && file.size > maxSize) {          reasons.push(`${file.name} is over ${formatBytes(maxSize)}`);        } else if (room <= 0) {          reasons.push(            limit === 1 ? "Only one file at a time" : `You can add up to ${limit} files`,          );          break;        } else {          accepted.push(file);          room--;        }      }
      setRejections(reasons);      if (reasons.length) shake();      if (!accepted.length) return;
      const created: DropzoneFile[] = accepted.map((file) => ({        id: nextId(),        file,        status: upload ? "queued" : "done",        progress: upload ? 0 : 1,        preview: file.type.startsWith("image/") ? URL.createObjectURL(file) : undefined,      }));      setItems((prev) => [...prev, ...created]);      onFiles?.(accepted);      created.forEach((it) => void runUpload(it));    },    // eslint-disable-next-line react-hooks/exhaustive-deps    [disabled, limit, maxSize, onFiles, runUpload, upload, accept],  );
  const remove = (id: string) => {    const item = itemsRef.current.find((it) => it.id === id);    if (!item) return;    controllers.current.get(id)?.abort();    if (item.preview) URL.revokeObjectURL(item.preview);    setItems((list) => list.filter((it) => it.id !== id));    onRemove?.(item.file);  };
  const full = items.length >= limit;  const blocked = disabled || full;
  const title =    state === "reject"      ? "Some files aren't accepted"      : state === "over"        ? `Release to add ${dragCount > 1 ? `${dragCount} files` : "file"}`        : state === "armed"          ? "Drop it here"          : full            ? `${limit === 1 ? "File" : "Files"} added`            : label;
  const meta = [    rules.length ? rules.map((r) => r.replace(/^\./, "").replace("/*", "").toUpperCase()).join(", ") : null,    maxSize ? `up to ${formatBytes(maxSize)}` : null,    multiple && maxFiles ? `${maxFiles} files max` : !multiple ? "1 file" : null,  ]    .filter(Boolean)    .join(" · ");
  const lifted = state === "over" || state === "armed";
  return (    <div className={cn("w-full", className)}>      <motion.div        ref={zoneRef}        role="button"        tabIndex={blocked ? -1 : 0}        aria-disabled={blocked || undefined}        aria-describedby={`${baseId}-meta`}        aria-label={`${label}. ${hint}`}        data-state={state}        onClick={() => !blocked && inputRef.current?.click()}        onKeyDown={(e) => {          if (blocked) return;          if (e.key === "Enter" || e.key === " ") {            e.preventDefault();            inputRef.current?.click();          }        }}        onPaste={(e) => {          if (blocked) return;          const files = Array.from(e.clipboardData.files);          if (files.length) {            e.preventDefault();            addFiles(files);          }        }}        onDragEnter={(e) => {          if (!hasFiles(e) || blocked) return;          e.preventDefault();          zoneDepth.current++;          setDragCount(e.dataTransfer.items.length);          setState(dragLooksRejected(e.dataTransfer.items, rules) ? "reject" : "over");        }}        onDragOver={(e) => {          if (!hasFiles(e)) return;          e.preventDefault();          e.dataTransfer.dropEffect = blocked || state === "reject" ? "none" : "copy";        }}        onDragLeave={() => {          zoneDepth.current = Math.max(0, zoneDepth.current - 1);          if (zoneDepth.current === 0) setState((s) => (s === "idle" ? s : "armed"));        }}        onDrop={(e) => {          // Let it bubble: the window listener resets its own drag depth.          e.preventDefault();          zoneDepth.current = 0;          setState("idle");          if (!blocked) addFiles(e.dataTransfer.files);        }}        animate={{ scale: state === "over" && !reduce ? 1.015 : 1 }}        transition={SPRING}        className={cn(          "group relative flex min-h-[12rem] w-full flex-col items-center justify-center gap-3 overflow-hidden rounded-[20px] px-6 py-8 text-center outline-none",          "transition-colors duration-200 ease-out",          "focus-visible:ring-2 focus-visible:ring-(--color-focus) focus-visible:ring-offset-2 focus-visible:ring-offset-(--color-paper)",          state === "over"            ? "bg-(--color-paper-2)"            : state === "reject"              ? "bg-red-500/[0.04]"              : "bg-(--color-paper) hover:bg-(--color-paper-2)/50",          blocked ? "cursor-default" : "cursor-pointer",          disabled && "opacity-50",        )}      >        <DashedBorder state={state} reduce={reduce} />
        {/* Soft spotlight that blooms under the cursor's file */}        <motion.div          aria-hidden          className="pointer-events-none absolute inset-0"          initial={false}          animate={{ opacity: state === "over" ? 1 : 0 }}          transition={{ duration: 0.3 }}          style={{            background:              "radial-gradient(60% 60% at 50% 45%, color-mix(in oklch, var(--color-ink) 7%, transparent), transparent 70%)",          }}        />
        <FileStack lifted={lifted} reject={state === "reject"} reduce={reduce} />
        <div className="relative flex flex-col items-center gap-1">          <div className="relative h-5 overflow-hidden text-[14px] font-medium text-(--color-ink)">            <AnimatePresence initial={false} mode="popLayout">              <motion.span                key={title}                initial={reduce ? { opacity: 0 } : { y: 10, opacity: 0, filter: "blur(3px)" }}                animate={{ y: 0, opacity: 1, filter: "blur(0px)" }}                exit={reduce ? { opacity: 0 } : { y: -10, opacity: 0, filter: "blur(3px)" }}                transition={{ duration: 0.2, ease: EASE_OUT }}                className={cn("block whitespace-nowrap", state === "reject" && "text-red-600 dark:text-red-400")}              >                {title}              </motion.span>            </AnimatePresence>          </div>          <div className="text-[13px] text-(--color-neutral)">            {full ? (              "Remove one to add another"            ) : (              <>                {hint.replace(/browse/i, "").trim() || "or"}{" "}                <span className="text-(--color-ink) underline decoration-(--color-rule) underline-offset-4 transition-colors group-hover:decoration-(--color-ink)/40">                  browse                </span>              </>            )}          </div>          {meta ? (            <div id={`${baseId}-meta`} className="mt-1 text-[11px] tracking-wide text-(--color-neutral)/80">              {meta}            </div>          ) : null}        </div>
        <input          ref={inputRef}          type="file"          className="sr-only"          tabIndex={-1}          accept={accept}          multiple={multiple}          disabled={blocked}          onChange={(e) => {            addFiles(e.target.files);            e.target.value = "";          }}        />      </motion.div>
      {/* Rejections */}      <AnimatePresence initial={false}>        {rejections.length > 0 && (          <motion.div            key="rejections"            role="alert"            initial={{ opacity: 0, height: 0 }}            animate={{ opacity: 1, height: "auto" }}            exit={{ opacity: 0, height: 0 }}            transition={{ duration: 0.22, ease: EASE_OUT }}            className="overflow-hidden"          >            <div className="mt-2 flex items-start justify-between gap-3 rounded-[12px] bg-red-500/[0.06] px-3 py-2 text-[12px] text-red-700 dark:text-red-300">              <div role="list" className="min-w-0 space-y-0.5">                {rejections.map((r, i) => (                  <div role="listitem" key={i} className="truncate">{r}</div>                ))}              </div>              <button                type="button"                aria-label="Dismiss"                onClick={() => setRejections([])}                className="-mr-1 grid size-5 shrink-0 place-items-center rounded-full outline-none hover:bg-red-500/10 focus-visible:ring-2 focus-visible:ring-(--color-focus)"              >                <X className="size-3" aria-hidden />              </button>            </div>          </motion.div>        )}      </AnimatePresence>
      {/* File list */}      {showList && (        <div role="list" aria-label="Files" className="mt-2 flex flex-col">          <AnimatePresence initial={false}>            {items.map((item) => (              <FileRow                key={item.id}                item={item}                reduce={reduce}                onRemove={() => remove(item.id)}                onRetry={() => void runUpload(item)}              />            ))}          </AnimatePresence>        </div>      )}    </div>  );}
/* ── Pieces ──────────────────────────────────────────────── */
/** SVG dashes so the border can actually be dashed, and march while dragging. */function DashedBorder({ state, reduce }: { state: ZoneState; reduce: boolean | null }) {  const active = state === "over" || state === "armed";  return (    <svg aria-hidden className="pointer-events-none absolute inset-px h-[calc(100%-2px)] w-[calc(100%-2px)] overflow-visible">      <motion.rect        width="100%"        height="100%"        rx="19"        fill="none"        strokeWidth={state === "over" ? 2 : 1.5}        strokeDasharray="7 7"        strokeLinecap="round"        className={cn(          "transition-[stroke] duration-200",          state === "reject"            ? "stroke-red-500/70"            : active              ? "stroke-(--color-ink)/55"              : "stroke-(--color-ink)/18 group-hover:stroke-(--color-ink)/30",        )}        animate={active && !reduce ? { strokeDashoffset: [0, -28] } : { strokeDashoffset: 0 }}        transition={active && !reduce ? { duration: 0.9, ease: "linear", repeat: Infinity } : { duration: 0 }}      />    </svg>  );}
/** Three sheets that fan out and lift when a file hovers the zone. */function FileStack({ lifted, reject, reduce }: { lifted: boolean; reject: boolean; reduce: boolean | null }) {  const sheet =    "absolute inset-0 rounded-[10px] border bg-(--color-paper) shadow-[0_1px_2px_rgba(0,0,0,0.05),0_6px_16px_rgba(0,0,0,0.06)]";  const t = reduce ? { duration: 0 } : SPRING;  return (    <div aria-hidden className="relative h-14 w-11">      <motion.div        className={cn(sheet, "border-(--color-rule)")}        initial={false}        animate={lifted ? { rotate: -14, x: -14, y: 2 } : { rotate: -6, x: -5, y: 2 }}        transition={t}      />      <motion.div        className={cn(sheet, "border-(--color-rule)")}        initial={false}        animate={lifted ? { rotate: 14, x: 14, y: 2 } : { rotate: 6, x: 5, y: 2 }}        transition={t}      />      <motion.div        className={cn(          sheet,          "grid place-items-center",          reject ? "border-red-500/40 text-red-500" : "border-(--color-ink)/15 text-(--color-ink)",        )}        initial={false}        animate={lifted ? { y: -8, scale: 1.06 } : reject ? { y: 0, scale: 1, rotate: [0, -6, 6, 0] } : { y: 0, scale: 1 }}        transition={t}      >        <motion.svg          width="18"          height="18"          viewBox="0 0 24 24"          fill="none"          stroke="currentColor"          strokeWidth="1.8"          strokeLinecap="round"          strokeLinejoin="round"          initial={false}          animate={{ y: lifted && !reduce ? -2 : 0 }}          transition={t}        >          {reject ? (            <path d="M7 7l10 10M17 7L7 17" />          ) : (            <>              <path d="M12 17V7" />              <path d="M7.5 11.5L12 7l4.5 4.5" />            </>          )}        </motion.svg>      </motion.div>    </div>  );}
function FileRow({  item,  reduce,  onRemove,  onRetry,}: {  item: DropzoneFile;  reduce: boolean | null;  onRemove: () => void;  onRetry: () => void;}) {  const [base, ext] = splitName(item.file.name);  const pct = Math.round(item.progress * 100);  const uploading = item.status === "uploading" || item.status === "queued";
  return (    <motion.div      role="listitem"      layout={!reduce}      initial={reduce ? { opacity: 0 } : { opacity: 0, height: 0, y: -6, filter: "blur(4px)" }}      animate={{ opacity: 1, height: "auto", y: 0, filter: "blur(0px)" }}      exit={reduce ? { opacity: 0 } : { opacity: 0, height: 0, filter: "blur(4px)", transition: { duration: 0.18 } }}      transition={{ duration: 0.28, ease: EASE_OUT }}      className="overflow-hidden"    >      <div className="mt-1.5 flex items-center gap-3 rounded-[14px] border border-(--color-rule) bg-(--color-paper) p-2 pr-2.5">        <div className="relative grid size-10 shrink-0 place-items-center overflow-hidden rounded-[9px] bg-(--color-paper-2) text-(--color-neutral)">          {item.preview ? (            // eslint-disable-next-line @next/next/no-img-element            <img src={item.preview} alt="" className="h-full w-full object-cover" />          ) : (            <>              <FileText className="size-4" strokeWidth={1.6} aria-hidden />              {ext ? (                <span className="absolute bottom-0.5 text-[8px] font-semibold tracking-wide uppercase">                  {ext.slice(1, 5)}                </span>              ) : null}            </>          )}        </div>
        <div className="min-w-0 flex-1">          <div className="flex min-w-0 text-[13px] font-medium text-(--color-ink)" title={item.file.name}>            <span className="truncate">{base}</span>            <span className="shrink-0">{ext}</span>          </div>          <div className="mt-0.5 flex items-center gap-2 text-[11px] text-(--color-neutral) tabular-nums">            <span>{formatBytes(item.file.size)}</span>            <span aria-hidden>·</span>            <span              className={cn(                item.status === "error" && "text-red-600 dark:text-red-400",                item.status === "done" && "text-emerald-600 dark:text-emerald-400",              )}            >              {item.status === "error"                ? item.error                : item.status === "done"                  ? "Ready"                  : item.status === "queued"                    ? "Waiting…"                    : `${pct}%`}            </span>          </div>          <AnimatePresence initial={false}>            {uploading && (              <motion.div                key="bar"                exit={{ opacity: 0, transition: { duration: 0.2, delay: 0.15 } }}                className="mt-1.5 h-1 overflow-hidden rounded-full bg-(--color-rule)"                role="progressbar"                aria-label={`Uploading ${item.file.name}`}                aria-valuemin={0}                aria-valuemax={100}                aria-valuenow={pct}              >                <motion.div                  className="h-full rounded-full bg-(--color-ink)"                  initial={false}                  animate={{ width: `${Math.max(4, pct)}%` }}                  transition={{ duration: 0.25, ease: "easeOut" }}                />              </motion.div>            )}          </AnimatePresence>        </div>
        <div className="flex shrink-0 items-center gap-1">          <AnimatePresence initial={false} mode="popLayout">            {item.status === "done" && (              <motion.span                key="done"                initial={reduce ? { opacity: 0 } : { scale: 0.4, opacity: 0, filter: "blur(2px)" }}                animate={{ scale: 1, opacity: 1, filter: "blur(0px)" }}                exit={{ opacity: 0 }}                transition={SPRING}                className="grid size-6 place-items-center rounded-full bg-emerald-500/12 text-emerald-600 dark:text-emerald-400"              >                <Check className="size-3.5" strokeWidth={2.5} aria-hidden />              </motion.span>            )}            {item.status === "error" && (              <motion.button                key="retry"                type="button"                aria-label={`Retry ${item.file.name}`}                onClick={onRetry}                initial={{ scale: 0.6, opacity: 0 }}                animate={{ scale: 1, opacity: 1 }}                exit={{ opacity: 0 }}                className="grid size-7 place-items-center rounded-full text-(--color-ink-2) outline-none hover:bg-(--color-paper-2) focus-visible:ring-2 focus-visible:ring-(--color-focus)"              >                <RotateCcw className="size-3.5" aria-hidden />              </motion.button>            )}          </AnimatePresence>          <button            type="button"            aria-label={`${uploading ? "Cancel" : "Remove"} ${item.file.name}`}            onClick={onRemove}            className="grid size-7 place-items-center rounded-full text-(--color-neutral) outline-none transition-colors hover:bg-(--color-paper-2) hover:text-(--color-ink) focus-visible:ring-2 focus-visible:ring-(--color-focus)"          >            <X className="size-3.5" aria-hidden />          </button>        </div>      </div>    </motion.div>  );}

Adjust import paths according to your folder structure.


Basic Usage

tsx
import { FileDropzone } from "@/components/ui/file-dropzone";
<FileDropzone  accept=".png,.jpg,.pdf"  onFiles={(files) => upload(files)}/>

Props

PropTypeRequiredDefaultDescription
onFiles(files: File[]) => voidNo—Fires with accepted files.
upload(file: File, progress: (p: number) => void, signal: AbortSignal) => Promise<void>No—Optional uploader. Report progress 0–1, throw to fail (shows retry). The signal aborts on cancel.
onRemove(file: File) => voidNo—Fires when a file is removed or cancelled.
maxSizenumberNo—Per-file size limit in bytes.
maxFilesnumberNo—Maximum files the list holds.
showListbooleanNotrueRender the built-in file list.
hintstringNo"or click to browse"Secondary line; the word “browse” is styled as the link.
acceptstringNo—MIME / extension filter (same as input accept).
multiplebooleanNotrueAllow multiple files.
disabledbooleanNo—Disables drop and click.
labelstringNo—Primary idle label.

Best Practices

  1. Always pair with accept when the backend is strict.
  2. Validate per file — never reject a whole batch for one bad file, and say why each was refused.
  3. Prevent drops outside the zone from navigating the tab to the file.
  4. Pass an upload function with an AbortSignal so removing a file actually cancels the request.