File dropzone

A drag-and-drop file area with a keyboard-reachable browse button backed by a native file input. Validates type (accept rules also apply to dropped files), size and count, explains rejected files, skips duplicates, and lists chosen files with an icon, size and a remove button that keeps keyboard focus in place. Changes are announced to screen readers. It only collects files; uploading is left to you.

Forms & inputsComponentTailwind v4

Source

"use client";

import { useEffect, useId, useRef, useState, type ChangeEvent, type DragEvent, type ReactNode } from "react";
import { File as FileIcon, FileArchive, FileImage, FileSpreadsheet, FileText, Upload, X } from "lucide-react";
import { cn } from "@/lib/utils";

export interface FileDropzoneProps {
  /** Visible label above the drop area. */
  label?: ReactNode;
  /** Same format as the input's accept attribute, such as ".pdf,image/*". Also enforced for dropped files. */
  accept?: string;
  multiple?: boolean;
  /** Largest allowed file, in bytes. */
  maxSize?: number;
  maxFiles?: number;
  files?: File[];
  defaultFiles?: File[];
  onFilesChange?: (files: File[]) => void;
  /** Short line under the prompt, such as "PDF or PNG, up to 10 MB". */
  hint?: ReactNode;
  disabled?: boolean;
  className?: string;
}

export function formatBytes(bytes: number) {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(bytes < 10 * 1024 ? 1 : 0)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

function matchesAccept(file: File, accept?: string) {
  if (!accept) return true;
  const name = file.name.toLowerCase();
  const type = file.type.toLowerCase();
  return accept.split(",").map((rule) => rule.trim().toLowerCase()).filter(Boolean).some((rule) =>
    rule.startsWith(".") ? name.endsWith(rule) : rule.endsWith("/*") ? type.startsWith(rule.slice(0, -1)) : type === rule);
}

function iconFor(file: File) {
  const ext = file.name.split(".").pop()?.toLowerCase() ?? "";
  if (file.type.startsWith("image/")) return FileImage;
  if (["csv", "xls", "xlsx", "numbers", "ods"].includes(ext)) return FileSpreadsheet;
  if (["zip", "gz", "tar", "rar", "7z"].includes(ext)) return FileArchive;
  if (file.type === "application/pdf" || ["pdf", "txt", "md", "doc", "docx", "rtf"].includes(ext)) return FileText;
  return FileIcon;
}

const keyOf = (file: File) => `${file.name}:${file.size}:${file.lastModified}`;

export function FileDropzone({
  label, accept, multiple = true, maxSize, maxFiles, files: controlled, defaultFiles = [], onFilesChange, hint,
  disabled, className,
}: FileDropzoneProps) {
  const id = useId();
  const [uncontrolled, setUncontrolled] = useState<File[]>(defaultFiles);
  const files = controlled ?? uncontrolled;
  const [dragging, setDragging] = useState(false);
  const [rejected, setRejected] = useState<{ name: string; reason: string }[]>([]);
  const [announcement, setAnnouncement] = useState("");
  const inputRef = useRef<HTMLInputElement>(null);
  const browseRef = useRef<HTMLButtonElement>(null);
  const removeRefs = useRef(new Map<string, HTMLButtonElement>());
  const dragDepth = useRef(0);
  const pendingFocus = useRef<string | null>(null);

  function update(next: File[]) {
    if (controlled === undefined) setUncontrolled(next);
    onFilesChange?.(next);
  }

  function addFiles(incoming: File[]) {
    if (disabled || !incoming.length) return;
    const known = new Set(files.map(keyOf));
    const accepted: File[] = [];
    const problems: { name: string; reason: string }[] = [];
    const limit = multiple ? maxFiles ?? Infinity : 1;
    for (const file of multiple ? incoming : incoming.slice(0, 1)) {
      if (known.has(keyOf(file))) continue;
      if (!matchesAccept(file, accept)) problems.push({ name: file.name, reason: "This file type isn't accepted." });
      else if (maxSize && file.size > maxSize) problems.push({ name: file.name, reason: `Larger than ${formatBytes(maxSize)}.` });
      else if ((multiple ? files.length : 0) + accepted.length >= limit) problems.push({ name: file.name, reason: `Only ${limit} ${limit === 1 ? "file" : "files"} allowed.` });
      else {
        accepted.push(file);
        known.add(keyOf(file));
      }
    }
    setRejected(problems);
    if (accepted.length) {
      update(multiple ? [...files, ...accepted] : accepted);
      setAnnouncement(`Added ${accepted.length} ${accepted.length === 1 ? "file" : "files"}.`);
    }
  }

  function remove(file: File) {
    const index = files.indexOf(file);
    const next = files.filter((item) => item !== file);
    // Keep keyboard users in place: focus the neighbouring remove button, or Browse when the list empties.
    const neighbour = next[index] ?? next[index - 1];
    pendingFocus.current = neighbour ? keyOf(neighbour) : "browse";
    update(next);
    setAnnouncement(`Removed ${file.name}.`);
  }

  useEffect(() => {
    const target = pendingFocus.current;
    if (!target) return;
    pendingFocus.current = null;
    (target === "browse" ? browseRef.current : removeRefs.current.get(target))?.focus();
  }, [files]);

  function hasFiles(event: DragEvent) {
    return Array.from(event.dataTransfer.types).includes("Files");
  }

  const dragProps = {
    onDragEnter(event: DragEvent<HTMLDivElement>) {
      if (disabled || !hasFiles(event)) return;
      event.preventDefault();
      dragDepth.current += 1;
      setDragging(true);
    },
    onDragOver(event: DragEvent<HTMLDivElement>) {
      if (disabled || !hasFiles(event)) return;
      event.preventDefault();
      event.dataTransfer.dropEffect = "copy";
    },
    onDragLeave() {
      dragDepth.current = Math.max(0, dragDepth.current - 1);
      if (dragDepth.current === 0) setDragging(false);
    },
    onDrop(event: DragEvent<HTMLDivElement>) {
      if (disabled) return;
      event.preventDefault();
      dragDepth.current = 0;
      setDragging(false);
      addFiles(Array.from(event.dataTransfer.files));
    },
  };

  function handleInput(event: ChangeEvent<HTMLInputElement>) {
    addFiles(Array.from(event.target.files ?? []));
    event.target.value = ""; // allows choosing the same file again after removing it
  }

  const labelId = `${id}-label`;
  const hintId = `${id}-hint`;

  return (
    <div className={cn("flex flex-col gap-3", className)}>
      {label && <span id={labelId} className="text-sm font-medium text-foreground">{label}</span>}

      <div
        {...dragProps}
        role="group"
        aria-labelledby={label ? labelId : undefined}
        data-dragging={dragging || undefined}
        data-disabled={disabled || undefined}
        onClick={(event) => {
          if (!disabled && !(event.target as HTMLElement).closest("button")) inputRef.current?.click();
        }}
        className={cn(
          "relative flex cursor-pointer flex-col items-center justify-center gap-3 rounded-xl border border-dashed border-foreground/20",
          "bg-muted/40 px-6 py-8 text-center transition-[background-color,border-color,box-shadow] duration-150",
          "hover:border-foreground/30 hover:bg-muted/60 dark:bg-muted/25 dark:hover:bg-muted/40",
          "data-[dragging]:border-ring data-[dragging]:bg-accent data-[dragging]:ring-[3px] data-[dragging]:ring-ring/25",
          "data-[disabled]:cursor-not-allowed data-[disabled]:opacity-60",
        )}
      >
        <span
          aria-hidden="true"
          className={cn(
            "grid size-10 place-items-center rounded-full border border-border bg-background text-muted-foreground shadow-xs",
            "motion-safe:transition-transform motion-safe:duration-200",
            dragging && "text-foreground motion-safe:-translate-y-0.5",
          )}
        >
          <Upload className="size-[18px]" />
        </span>
        <div className="flex flex-col items-center gap-1">
          <p className="text-sm text-foreground">
            {dragging ? "Drop to add" : (
              <>
                <span className="font-medium">Drag files here</span>
                <span className="text-muted-foreground"> or </span>
                <button
                  ref={browseRef}
                  type="button"
                  disabled={disabled}
                  aria-describedby={hint ? hintId : undefined}
                  onClick={() => inputRef.current?.click()}
                  className="rounded-sm font-medium text-foreground underline decoration-foreground/30 underline-offset-4 outline-hidden hover:decoration-foreground focus-visible:ring-[3px] focus-visible:ring-ring/50"
                >
                  browse
                </button>
              </>
            )}
          </p>
          {hint && <p id={hintId} className="text-xs text-muted-foreground">{hint}</p>}
        </div>
        <input
          ref={inputRef}
          type="file"
          className="hidden"
          tabIndex={-1}
          accept={accept}
          multiple={multiple}
          disabled={disabled}
          onChange={handleInput}
        />
      </div>

      {rejected.length > 0 && (
        <ul role="alert" className="flex flex-col gap-1 rounded-lg border border-destructive/25 bg-destructive/5 px-3 py-2 text-[13px]">
          {rejected.map((item, index) => (
            <li key={`${item.name}-${index}`} className="flex min-w-0 gap-1.5 text-destructive">
              <span className="truncate font-medium">{item.name}</span>
              <span className="shrink-0">{item.reason}</span>
            </li>
          ))}
        </ul>
      )}

      {files.length > 0 && (
        <ul aria-label="Selected files" className="flex flex-col divide-y divide-border rounded-xl border border-border bg-card">
          {files.map((file) => {
            const Icon = iconFor(file);
            const ext = file.name.includes(".") ? file.name.split(".").pop()!.toUpperCase() : "FILE";
            return (
              <li key={keyOf(file)} className="flex items-center gap-3 py-2.5 pl-3 pr-2">
                <span aria-hidden="true" className="grid size-9 shrink-0 place-items-center rounded-lg border border-border bg-muted/60 text-muted-foreground">
                  <Icon className="size-[18px]" />
                </span>
                <div className="flex min-w-0 flex-1 flex-col">
                  <span className="truncate text-sm font-medium text-foreground">{file.name}</span>
                  <span className="text-xs tabular-nums text-muted-foreground">{formatBytes(file.size)} · {ext}</span>
                </div>
                <button
                  ref={(node) => {
                    if (node) removeRefs.current.set(keyOf(file), node);
                    else removeRefs.current.delete(keyOf(file));
                  }}
                  type="button"
                  aria-label={`Remove ${file.name}`}
                  disabled={disabled}
                  onClick={() => remove(file)}
                  className="inline-flex size-8 shrink-0 items-center justify-center rounded-md text-muted-foreground outline-hidden transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-[3px] focus-visible:ring-ring/50"
                >
                  <X aria-hidden="true" className="size-4" />
                </button>
              </li>
            );
          })}
        </ul>
      )}

      <span role="status" className="sr-only">{announcement}</span>
    </div>
  );
}