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.jsonInstall dependencies:
$ pnpm add motion lucide-reactAdd the utility function for class merging:
lib/utils.ts
tsx
1import { ClassValue, clsx } from "clsx";2import { twMerge } from "tailwind-merge";3 4export function cn(...inputs: ClassValue[]) {5 return twMerge(clsx(inputs));6}
Copy the component code into your project:
tsx
1"use client";2 3import React, { useCallback, useEffect, useId, useRef, useState } from "react";4import {5 AnimatePresence,6 motion,7 useAnimate,8 useReducedMotion,9} from "motion/react";10import { Check, FileText, RotateCcw, X } from "lucide-react";11import { cn } from "@/lib/utils";12 13export type DropzoneFileStatus = "queued" | "uploading" | "done" | "error";14 15export type DropzoneFile = {16 id: string;17 file: File;18 status: DropzoneFileStatus;19 progress: number;20 preview?: string;21 error?: string;22};23 24export type FileDropzoneProps = {25 /** Fires with each batch of accepted files. */26 onFiles?: (files: File[]) => void;27 /**28 * Optional uploader. Call `progress(0–1)` as bytes go out; throw to fail.29 * The signal aborts when the user removes the file mid-upload.30 */31 upload?: (file: File, progress: (p: number) => void, signal: AbortSignal) => Promise<void>;32 onRemove?: (file: File) => void;33 accept?: string;34 multiple?: boolean;35 /** Per-file size limit in bytes. */36 maxSize?: number;37 /** Total files the list will hold. */38 maxFiles?: number;39 disabled?: boolean;40 /** Render the built-in file list under the zone. */41 showList?: boolean;42 className?: string;43 label?: string;44 hint?: string;45};46 47type ZoneState = "idle" | "armed" | "over" | "reject";48 49const EASE_OUT = [0.23, 1, 0.32, 1] as const;50const SPRING = { type: "spring" as const, bounce: 0.2, duration: 0.45 };51 52/* ── Helpers ─────────────────────────────────────────────── */53 54function formatBytes(bytes: number) {55 if (bytes < 1024) return `${bytes} B`;56 const units = ["KB", "MB", "GB"];57 let n = bytes / 1024;58 let i = 0;59 while (n >= 1024 && i < units.length - 1) {60 n /= 1024;61 i++;62 }63 return `${n < 10 ? n.toFixed(1) : Math.round(n)} ${units[i]}`;64}65 66function acceptList(accept?: string) {67 return accept ? accept.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean) : [];68}69 70function matchesAccept(name: string, type: string, rules: string[]) {71 if (!rules.length) return true;72 const lower = name.toLowerCase();73 return rules.some((r) => {74 if (r.startsWith(".")) return lower.endsWith(r);75 if (r.endsWith("/*")) return type.startsWith(r.slice(0, -1));76 return type === r;77 });78}79 80/** During a drag only MIME types are visible; extensions can't be checked yet. */81function dragLooksRejected(items: DataTransferItemList, rules: string[]) {82 const mimeRules = rules.filter((r) => !r.startsWith("."));83 if (!mimeRules.length || rules.length !== mimeRules.length) return false;84 return Array.from(items).some(85 (it) => it.kind === "file" && it.type && !matchesAccept("", it.type, mimeRules),86 );87}88 89function hasFiles(e: DragEvent | React.DragEvent) {90 return Array.from(e.dataTransfer?.types ?? []).includes("Files");91}92 93function splitName(name: string) {94 const dot = name.lastIndexOf(".");95 return dot > 0 ? [name.slice(0, dot), name.slice(dot)] : [name, ""];96}97 98let uid = 0;99const nextId = () => `f${Date.now().toString(36)}${(uid++).toString(36)}`;100 101/* ── Component ───────────────────────────────────────────── */102 103export function FileDropzone({104 onFiles,105 upload,106 onRemove,107 accept,108 multiple = true,109 maxSize,110 maxFiles,111 disabled,112 showList = true,113 className,114 label = "Drop files here",115 hint = "or click to browse",116}: FileDropzoneProps) {117 const reduce = useReducedMotion();118 const baseId = useId();119 const inputRef = useRef<HTMLInputElement>(null);120 const [zoneRef, animateZone] = useAnimate<HTMLDivElement>();121 const [state, setState] = useState<ZoneState>("idle");122 const [dragCount, setDragCount] = useState(0);123 const [items, setItems] = useState<DropzoneFile[]>([]);124 const [rejections, setRejections] = useState<string[]>([]);125 const itemsRef = useRef(items);126 itemsRef.current = items;127 const controllers = useRef(new Map<string, AbortController>());128 const zoneDepth = useRef(0);129 130 const rules = acceptList(accept);131 const limit = multiple ? (maxFiles ?? Infinity) : 1;132 133 /* Window-level drag: arm the zone when a file enters the page, and stop a134 drop that misses the zone from navigating the tab to the file. */135 useEffect(() => {136 if (disabled) return;137 let depth = 0;138 const enter = (e: DragEvent) => {139 if (!hasFiles(e)) return;140 depth++;141 setState((s) => (s === "idle" ? "armed" : s));142 };143 const leave = (e: DragEvent) => {144 if (!hasFiles(e)) return;145 depth = Math.max(0, depth - 1);146 if (depth === 0) setState("idle");147 };148 const over = (e: DragEvent) => {149 if (!hasFiles(e)) return;150 e.preventDefault();151 if (e.dataTransfer && zoneDepth.current === 0) e.dataTransfer.dropEffect = "none";152 };153 const drop = (e: DragEvent) => {154 depth = 0;155 if (!hasFiles(e)) return;156 e.preventDefault();157 setState("idle");158 };159 window.addEventListener("dragenter", enter);160 window.addEventListener("dragleave", leave);161 window.addEventListener("dragover", over);162 window.addEventListener("drop", drop);163 return () => {164 window.removeEventListener("dragenter", enter);165 window.removeEventListener("dragleave", leave);166 window.removeEventListener("dragover", over);167 window.removeEventListener("drop", drop);168 };169 }, [disabled]);170 171 // Revoke previews and abort uploads on unmount.172 useEffect(173 () => () => {174 itemsRef.current.forEach((it) => it.preview && URL.revokeObjectURL(it.preview));175 controllers.current.forEach((c) => c.abort());176 },177 [],178 );179 180 const patch = (id: string, next: Partial<DropzoneFile>) =>181 setItems((list) => list.map((it) => (it.id === id ? { ...it, ...next } : it)));182 183 const runUpload = useCallback(184 async (item: DropzoneFile) => {185 if (!upload) return;186 const controller = new AbortController();187 controllers.current.set(item.id, controller);188 patch(item.id, { status: "uploading", progress: 0, error: undefined });189 try {190 await upload(191 item.file,192 (p) => patch(item.id, { progress: Math.min(1, Math.max(0, p)) }),193 controller.signal,194 );195 if (!controller.signal.aborted) patch(item.id, { status: "done", progress: 1 });196 } catch (err) {197 if (controller.signal.aborted) return;198 patch(item.id, {199 status: "error",200 error: err instanceof Error && err.message ? err.message : "Upload failed",201 });202 } finally {203 controllers.current.delete(item.id);204 }205 },206 [upload],207 );208 209 const shake = () => {210 if (reduce || !zoneRef.current) return;211 animateZone(zoneRef.current, { x: [0, -8, 7, -5, 3, 0] }, { duration: 0.4, ease: "easeOut" });212 };213 214 const addFiles = useCallback(215 (list: FileList | File[] | null) => {216 if (!list || disabled) return;217 const incoming = Array.from(list);218 if (!incoming.length) return;219 220 const reasons: string[] = [];221 const accepted: File[] = [];222 let room = limit - itemsRef.current.length;223 224 for (const file of incoming) {225 if (!matchesAccept(file.name, file.type, rules)) {226 reasons.push(`${file.name} isn't an accepted type`);227 } else if (maxSize && file.size > maxSize) {228 reasons.push(`${file.name} is over ${formatBytes(maxSize)}`);229 } else if (room <= 0) {230 reasons.push(231 limit === 1 ? "Only one file at a time" : `You can add up to ${limit} files`,232 );233 break;234 } else {235 accepted.push(file);236 room--;237 }238 }239 240 setRejections(reasons);241 if (reasons.length) shake();242 if (!accepted.length) return;243 244 const created: DropzoneFile[] = accepted.map((file) => ({245 id: nextId(),246 file,247 status: upload ? "queued" : "done",248 progress: upload ? 0 : 1,249 preview: file.type.startsWith("image/") ? URL.createObjectURL(file) : undefined,250 }));251 setItems((prev) => [...prev, ...created]);252 onFiles?.(accepted);253 created.forEach((it) => void runUpload(it));254 },255 // eslint-disable-next-line react-hooks/exhaustive-deps256 [disabled, limit, maxSize, onFiles, runUpload, upload, accept],257 );258 259 const remove = (id: string) => {260 const item = itemsRef.current.find((it) => it.id === id);261 if (!item) return;262 controllers.current.get(id)?.abort();263 if (item.preview) URL.revokeObjectURL(item.preview);264 setItems((list) => list.filter((it) => it.id !== id));265 onRemove?.(item.file);266 };267 268 const full = items.length >= limit;269 const blocked = disabled || full;270 271 const title =272 state === "reject"273 ? "Some files aren't accepted"274 : state === "over"275 ? `Release to add ${dragCount > 1 ? `${dragCount} files` : "file"}`276 : state === "armed"277 ? "Drop it here"278 : full279 ? `${limit === 1 ? "File" : "Files"} added`280 : label;281 282 const meta = [283 rules.length ? rules.map((r) => r.replace(/^\./, "").replace("/*", "").toUpperCase()).join(", ") : null,284 maxSize ? `up to ${formatBytes(maxSize)}` : null,285 multiple && maxFiles ? `${maxFiles} files max` : !multiple ? "1 file" : null,286 ]287 .filter(Boolean)288 .join(" · ");289 290 const lifted = state === "over" || state === "armed";291 292 return (293 <div className={cn("w-full", className)}>294 <motion.div295 ref={zoneRef}296 role="button"297 tabIndex={blocked ? -1 : 0}298 aria-disabled={blocked || undefined}299 aria-describedby={`${baseId}-meta`}300 aria-label={`${label}. ${hint}`}301 data-state={state}302 onClick={() => !blocked && inputRef.current?.click()}303 onKeyDown={(e) => {304 if (blocked) return;305 if (e.key === "Enter" || e.key === " ") {306 e.preventDefault();307 inputRef.current?.click();308 }309 }}310 onPaste={(e) => {311 if (blocked) return;312 const files = Array.from(e.clipboardData.files);313 if (files.length) {314 e.preventDefault();315 addFiles(files);316 }317 }}318 onDragEnter={(e) => {319 if (!hasFiles(e) || blocked) return;320 e.preventDefault();321 zoneDepth.current++;322 setDragCount(e.dataTransfer.items.length);323 setState(dragLooksRejected(e.dataTransfer.items, rules) ? "reject" : "over");324 }}325 onDragOver={(e) => {326 if (!hasFiles(e)) return;327 e.preventDefault();328 e.dataTransfer.dropEffect = blocked || state === "reject" ? "none" : "copy";329 }}330 onDragLeave={() => {331 zoneDepth.current = Math.max(0, zoneDepth.current - 1);332 if (zoneDepth.current === 0) setState((s) => (s === "idle" ? s : "armed"));333 }}334 onDrop={(e) => {335 // Let it bubble: the window listener resets its own drag depth.336 e.preventDefault();337 zoneDepth.current = 0;338 setState("idle");339 if (!blocked) addFiles(e.dataTransfer.files);340 }}341 animate={{ scale: state === "over" && !reduce ? 1.015 : 1 }}342 transition={SPRING}343 className={cn(344 "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",345 "transition-colors duration-200 ease-out",346 "focus-visible:ring-2 focus-visible:ring-(--color-focus) focus-visible:ring-offset-2 focus-visible:ring-offset-(--color-paper)",347 state === "over"348 ? "bg-(--color-paper-2)"349 : state === "reject"350 ? "bg-red-500/[0.04]"351 : "bg-(--color-paper) hover:bg-(--color-paper-2)/50",352 blocked ? "cursor-default" : "cursor-pointer",353 disabled && "opacity-50",354 )}355 >356 <DashedBorder state={state} reduce={reduce} />357 358 {/* Soft spotlight that blooms under the cursor's file */}359 <motion.div360 aria-hidden361 className="pointer-events-none absolute inset-0"362 initial={false}363 animate={{ opacity: state === "over" ? 1 : 0 }}364 transition={{ duration: 0.3 }}365 style={{366 background:367 "radial-gradient(60% 60% at 50% 45%, color-mix(in oklch, var(--color-ink) 7%, transparent), transparent 70%)",368 }}369 />370 371 <FileStack lifted={lifted} reject={state === "reject"} reduce={reduce} />372 373 <div className="relative flex flex-col items-center gap-1">374 <div className="relative h-5 overflow-hidden text-[14px] font-medium text-(--color-ink)">375 <AnimatePresence initial={false} mode="popLayout">376 <motion.span377 key={title}378 initial={reduce ? { opacity: 0 } : { y: 10, opacity: 0, filter: "blur(3px)" }}379 animate={{ y: 0, opacity: 1, filter: "blur(0px)" }}380 exit={reduce ? { opacity: 0 } : { y: -10, opacity: 0, filter: "blur(3px)" }}381 transition={{ duration: 0.2, ease: EASE_OUT }}382 className={cn("block whitespace-nowrap", state === "reject" && "text-red-600 dark:text-red-400")}383 >384 {title}385 </motion.span>386 </AnimatePresence>387 </div>388 <div className="text-[13px] text-(--color-neutral)">389 {full ? (390 "Remove one to add another"391 ) : (392 <>393 {hint.replace(/browse/i, "").trim() || "or"}{" "}394 <span className="text-(--color-ink) underline decoration-(--color-rule) underline-offset-4 transition-colors group-hover:decoration-(--color-ink)/40">395 browse396 </span>397 </>398 )}399 </div>400 {meta ? (401 <div id={`${baseId}-meta`} className="mt-1 text-[11px] tracking-wide text-(--color-neutral)/80">402 {meta}403 </div>404 ) : null}405 </div>406 407 <input408 ref={inputRef}409 type="file"410 className="sr-only"411 tabIndex={-1}412 accept={accept}413 multiple={multiple}414 disabled={blocked}415 onChange={(e) => {416 addFiles(e.target.files);417 e.target.value = "";418 }}419 />420 </motion.div>421 422 {/* Rejections */}423 <AnimatePresence initial={false}>424 {rejections.length > 0 && (425 <motion.div426 key="rejections"427 role="alert"428 initial={{ opacity: 0, height: 0 }}429 animate={{ opacity: 1, height: "auto" }}430 exit={{ opacity: 0, height: 0 }}431 transition={{ duration: 0.22, ease: EASE_OUT }}432 className="overflow-hidden"433 >434 <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">435 <div role="list" className="min-w-0 space-y-0.5">436 {rejections.map((r, i) => (437 <div role="listitem" key={i} className="truncate">{r}</div>438 ))}439 </div>440 <button441 type="button"442 aria-label="Dismiss"443 onClick={() => setRejections([])}444 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)"445 >446 <X className="size-3" aria-hidden />447 </button>448 </div>449 </motion.div>450 )}451 </AnimatePresence>452 453 {/* File list */}454 {showList && (455 <div role="list" aria-label="Files" className="mt-2 flex flex-col">456 <AnimatePresence initial={false}>457 {items.map((item) => (458 <FileRow459 key={item.id}460 item={item}461 reduce={reduce}462 onRemove={() => remove(item.id)}463 onRetry={() => void runUpload(item)}464 />465 ))}466 </AnimatePresence>467 </div>468 )}469 </div>470 );471}472 473/* ── Pieces ──────────────────────────────────────────────── */474 475/** SVG dashes so the border can actually be dashed, and march while dragging. */476function DashedBorder({ state, reduce }: { state: ZoneState; reduce: boolean | null }) {477 const active = state === "over" || state === "armed";478 return (479 <svg aria-hidden className="pointer-events-none absolute inset-px h-[calc(100%-2px)] w-[calc(100%-2px)] overflow-visible">480 <motion.rect481 width="100%"482 height="100%"483 rx="19"484 fill="none"485 strokeWidth={state === "over" ? 2 : 1.5}486 strokeDasharray="7 7"487 strokeLinecap="round"488 className={cn(489 "transition-[stroke] duration-200",490 state === "reject"491 ? "stroke-red-500/70"492 : active493 ? "stroke-(--color-ink)/55"494 : "stroke-(--color-ink)/18 group-hover:stroke-(--color-ink)/30",495 )}496 animate={active && !reduce ? { strokeDashoffset: [0, -28] } : { strokeDashoffset: 0 }}497 transition={active && !reduce ? { duration: 0.9, ease: "linear", repeat: Infinity } : { duration: 0 }}498 />499 </svg>500 );501}502 503/** Three sheets that fan out and lift when a file hovers the zone. */504function FileStack({ lifted, reject, reduce }: { lifted: boolean; reject: boolean; reduce: boolean | null }) {505 const sheet =506 "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)]";507 const t = reduce ? { duration: 0 } : SPRING;508 return (509 <div aria-hidden className="relative h-14 w-11">510 <motion.div511 className={cn(sheet, "border-(--color-rule)")}512 initial={false}513 animate={lifted ? { rotate: -14, x: -14, y: 2 } : { rotate: -6, x: -5, y: 2 }}514 transition={t}515 />516 <motion.div517 className={cn(sheet, "border-(--color-rule)")}518 initial={false}519 animate={lifted ? { rotate: 14, x: 14, y: 2 } : { rotate: 6, x: 5, y: 2 }}520 transition={t}521 />522 <motion.div523 className={cn(524 sheet,525 "grid place-items-center",526 reject ? "border-red-500/40 text-red-500" : "border-(--color-ink)/15 text-(--color-ink)",527 )}528 initial={false}529 animate={lifted ? { y: -8, scale: 1.06 } : reject ? { y: 0, scale: 1, rotate: [0, -6, 6, 0] } : { y: 0, scale: 1 }}530 transition={t}531 >532 <motion.svg533 width="18"534 height="18"535 viewBox="0 0 24 24"536 fill="none"537 stroke="currentColor"538 strokeWidth="1.8"539 strokeLinecap="round"540 strokeLinejoin="round"541 initial={false}542 animate={{ y: lifted && !reduce ? -2 : 0 }}543 transition={t}544 >545 {reject ? (546 <path d="M7 7l10 10M17 7L7 17" />547 ) : (548 <>549 <path d="M12 17V7" />550 <path d="M7.5 11.5L12 7l4.5 4.5" />551 </>552 )}553 </motion.svg>554 </motion.div>555 </div>556 );557}558 559function FileRow({560 item,561 reduce,562 onRemove,563 onRetry,564}: {565 item: DropzoneFile;566 reduce: boolean | null;567 onRemove: () => void;568 onRetry: () => void;569}) {570 const [base, ext] = splitName(item.file.name);571 const pct = Math.round(item.progress * 100);572 const uploading = item.status === "uploading" || item.status === "queued";573 574 return (575 <motion.div576 role="listitem"577 layout={!reduce}578 initial={reduce ? { opacity: 0 } : { opacity: 0, height: 0, y: -6, filter: "blur(4px)" }}579 animate={{ opacity: 1, height: "auto", y: 0, filter: "blur(0px)" }}580 exit={reduce ? { opacity: 0 } : { opacity: 0, height: 0, filter: "blur(4px)", transition: { duration: 0.18 } }}581 transition={{ duration: 0.28, ease: EASE_OUT }}582 className="overflow-hidden"583 >584 <div className="mt-1.5 flex items-center gap-3 rounded-[14px] border border-(--color-rule) bg-(--color-paper) p-2 pr-2.5">585 <div className="relative grid size-10 shrink-0 place-items-center overflow-hidden rounded-[9px] bg-(--color-paper-2) text-(--color-neutral)">586 {item.preview ? (587 // eslint-disable-next-line @next/next/no-img-element588 <img src={item.preview} alt="" className="h-full w-full object-cover" />589 ) : (590 <>591 <FileText className="size-4" strokeWidth={1.6} aria-hidden />592 {ext ? (593 <span className="absolute bottom-0.5 text-[8px] font-semibold tracking-wide uppercase">594 {ext.slice(1, 5)}595 </span>596 ) : null}597 </>598 )}599 </div>600 601 <div className="min-w-0 flex-1">602 <div className="flex min-w-0 text-[13px] font-medium text-(--color-ink)" title={item.file.name}>603 <span className="truncate">{base}</span>604 <span className="shrink-0">{ext}</span>605 </div>606 <div className="mt-0.5 flex items-center gap-2 text-[11px] text-(--color-neutral) tabular-nums">607 <span>{formatBytes(item.file.size)}</span>608 <span aria-hidden>·</span>609 <span610 className={cn(611 item.status === "error" && "text-red-600 dark:text-red-400",612 item.status === "done" && "text-emerald-600 dark:text-emerald-400",613 )}614 >615 {item.status === "error"616 ? item.error617 : item.status === "done"618 ? "Ready"619 : item.status === "queued"620 ? "Waiting…"621 : `${pct}%`}622 </span>623 </div>624 <AnimatePresence initial={false}>625 {uploading && (626 <motion.div627 key="bar"628 exit={{ opacity: 0, transition: { duration: 0.2, delay: 0.15 } }}629 className="mt-1.5 h-1 overflow-hidden rounded-full bg-(--color-rule)"630 role="progressbar"631 aria-label={`Uploading ${item.file.name}`}632 aria-valuemin={0}633 aria-valuemax={100}634 aria-valuenow={pct}635 >636 <motion.div637 className="h-full rounded-full bg-(--color-ink)"638 initial={false}639 animate={{ width: `${Math.max(4, pct)}%` }}640 transition={{ duration: 0.25, ease: "easeOut" }}641 />642 </motion.div>643 )}644 </AnimatePresence>645 </div>646 647 <div className="flex shrink-0 items-center gap-1">648 <AnimatePresence initial={false} mode="popLayout">649 {item.status === "done" && (650 <motion.span651 key="done"652 initial={reduce ? { opacity: 0 } : { scale: 0.4, opacity: 0, filter: "blur(2px)" }}653 animate={{ scale: 1, opacity: 1, filter: "blur(0px)" }}654 exit={{ opacity: 0 }}655 transition={SPRING}656 className="grid size-6 place-items-center rounded-full bg-emerald-500/12 text-emerald-600 dark:text-emerald-400"657 >658 <Check className="size-3.5" strokeWidth={2.5} aria-hidden />659 </motion.span>660 )}661 {item.status === "error" && (662 <motion.button663 key="retry"664 type="button"665 aria-label={`Retry ${item.file.name}`}666 onClick={onRetry}667 initial={{ scale: 0.6, opacity: 0 }}668 animate={{ scale: 1, opacity: 1 }}669 exit={{ opacity: 0 }}670 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)"671 >672 <RotateCcw className="size-3.5" aria-hidden />673 </motion.button>674 )}675 </AnimatePresence>676 <button677 type="button"678 aria-label={`${uploading ? "Cancel" : "Remove"} ${item.file.name}`}679 onClick={onRemove}680 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)"681 >682 <X className="size-3.5" aria-hidden />683 </button>684 </div>685 </div>686 </motion.div>687 );688}
Adjust import paths according to your folder structure.
Basic Usage
tsx
1import { FileDropzone } from "@/components/ui/file-dropzone";2 3<FileDropzone4 accept=".png,.jpg,.pdf"5 onFiles={(files) => upload(files)}6/>
Props
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| onFiles | (files: File[]) => void | No | — | 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) => void | No | — | Fires when a file is removed or cancelled. |
| maxSize | number | No | — | Per-file size limit in bytes. |
| maxFiles | number | No | — | Maximum files the list holds. |
| showList | boolean | No | true | Render the built-in file list. |
| hint | string | No | "or click to browse" | Secondary line; the word “browse” is styled as the link. |
| accept | string | No | — | MIME / extension filter (same as input accept). |
| multiple | boolean | No | true | Allow multiple files. |
| disabled | boolean | No | — | Disables drop and click. |
| label | string | No | — | Primary idle label. |
Best Practices
- Always pair with
acceptwhen the backend is strict. - Validate per file — never reject a whole batch for one bad file, and say why each was refused.
- Prevent drops outside the zone from navigating the tab to the file.
- Pass an
uploadfunction with anAbortSignalso removing a file actually cancels the request.