Skip to content

NewMCP server for your coding agent. Set it up ›

Nexus UI
Get Pro
Skip to content

NewMCP server for your coding agent. Set it up ›

React File Upload with Drag and Drop and Progress

Build a drag and drop file upload in React and Tailwind CSS: validation, per-file progress with XMLHttpRequest, keyboard and screen reader support, retries, and what to add to make it feel finished.

A file upload looks like one feature but it is really five: take files from a drop or a file picker, reject the wrong ones with a reason, send the good ones, show how far each one has got, and let the person recover when one fails. Most tutorials cover the first and last of those in a few lines and stop, which is why so many upload boxes feel broken the moment someone drops a 300 MB video on them.

This guide builds a complete drag and drop uploader in React and Tailwind CSS with no library, then covers the details that decide whether it feels good: the flicker bug in drag events, why fetch cannot show upload progress, and how to make it usable from the keyboard and with a screen reader.

What a good dropzone does

Before the code, the behaviour worth getting right:

  1. It accepts files three ways: dropped on the zone, chosen from the system file picker, and (on desktop) pasted if you want that.
  2. It checks before it sends. Type and size are cheap to test in the browser, so refuse a bad file immediately and say why, instead of waiting for the server to reject it.
  3. Every file has its own row with its own progress and its own result. One failure must not stop the others.
  4. A failed file can be retried and any file can be removed.
  5. It works without a mouse. The zone is reachable with Tab and opens the picker with Enter or Space.

Reading dropped files

The browser gives you the dropped files on event.dataTransfer.files. Two things trip people up.

First, a drop only fires if you cancel the default behaviour on dragover. If you forget event.preventDefault() there, the browser navigates to the dropped file instead of calling your handler.

Second, the zone's own children fire dragenter and dragleave as the pointer moves across them, so a naive "highlight on enter, remove on leave" flickers constantly. The fix is a counter: add one on dragenter, subtract one on dragleave, and treat the zone as active while the count is above zero.

Validation

Keep the checks in one small function that returns a message or null, so the same function runs for dropped files and for files chosen in the picker.

const MAX_MB = 20;
const ALLOWED = ["image/", "application/pdf"];

function check(file: File): string | null {
  if (file.size > MAX_MB * 1024 * 1024) return `Too large: ${(file.size / 1048576).toFixed(0)} MB (max ${MAX_MB} MB)`;
  if (!ALLOWED.some((type) => file.type.startsWith(type))) return "That file type is not allowed";
  return null;
}

The browser's file.type comes from the file extension, so it is a convenience for the person using the page and not a security check. Always validate type and size again on the server.

Sending a file with real progress

fetch cannot report upload progress, because the request body is not exposed as a stream you can count in every browser. XMLHttpRequest still can, through xhr.upload.onprogress, so wrap it in a promise and report a number from 0 to 1.

function send(file: File, onProgress: (progress: number) => void): Promise<void> {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("POST", "/api/upload");
    xhr.upload.onprogress = (event) => {
      if (event.lengthComputable) onProgress(event.loaded / event.total);
    };
    xhr.onload = () =>
      xhr.status >= 200 && xhr.status < 300 ? resolve() : reject(new Error(`Upload failed (${xhr.status})`));
    xhr.onerror = () => reject(new Error("Network error"));
    const body = new FormData();
    body.append("file", file);
    xhr.send(body);
  });
}

Point /api/upload at your own route, or at a pre-signed URL from your storage provider if you upload straight to it.

The component

Put MAX_MB, check and send above it in the same file, or import them.

"use client";

import { useRef, useState, type DragEvent } from "react";

type Row = {
  id: number;
  file: File;
  progress: number;
  status: "uploading" | "done" | "error";
  message?: string;
};

export function FileDropzone() {
  const [rows, setRows] = useState<Row[]>([]);
  const [over, setOver] = useState(false);
  const depth = useRef(0);
  const nextId = useRef(0);

  function patch(id: number, change: Partial<Row>) {
    setRows((current) => current.map((row) => (row.id === id ? { ...row, ...change } : row)));
  }

  function upload(id: number, file: File) {
    patch(id, { status: "uploading", progress: 0, message: undefined });
    send(file, (progress) => patch(id, { progress }))
      .then(() => patch(id, { status: "done", progress: 1 }))
      .catch((error: Error) => patch(id, { status: "error", message: error.message }));
  }

  function add(files: Iterable<File>) {
    for (const file of files) {
      const id = nextId.current++;
      const problem = check(file);
      setRows((current) => [
        ...current,
        { id, file, progress: 0, status: problem ? "error" : "uploading", message: problem ?? undefined },
      ]);
      if (!problem) upload(id, file);
    }
  }

  function onDrop(event: DragEvent<HTMLLabelElement>) {
    event.preventDefault();
    depth.current = 0;
    setOver(false);
    add(Array.from(event.dataTransfer.files));
  }

  return (
    <div className="w-full max-w-md">
      <label
        onDragEnter={() => {
          depth.current += 1;
          setOver(true);
        }}
        onDragLeave={() => {
          depth.current -= 1;
          if (depth.current <= 0) setOver(false);
        }}
        onDragOver={(event) => event.preventDefault()}
        onDrop={onDrop}
        className={`flex cursor-pointer flex-col items-center gap-1 rounded-2xl border border-dashed p-8 text-center transition-colors has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-blue-500 ${
          over ? "border-blue-500 bg-blue-500/5" : "border-zinc-300 dark:border-zinc-700"
        }`}
      >
        <span className="text-sm font-medium">Drop files here or browse</span>
        <span className="text-xs text-zinc-500">Images and PDFs, up to {MAX_MB} MB each</span>
        <input
          type="file"
          multiple
          className="sr-only"
          onChange={(event) => {
            add(Array.from(event.target.files ?? []));
            event.target.value = "";
          }}
        />
      </label>

      <ul className="mt-4 space-y-2" aria-live="polite">
        {rows.map((row) => (
          <li key={row.id} className="rounded-xl border border-zinc-200 p-3 text-sm dark:border-zinc-800">
            <div className="flex items-center justify-between gap-3">
              <span className="truncate">{row.file.name}</span>
              <span className="shrink-0 text-xs text-zinc-500">
                {row.status === "done" ? "Uploaded" : row.status === "error" ? "Failed" : `${Math.round(row.progress * 100)}%`}
              </span>
            </div>
            {row.status === "error" ? (
              <div className="mt-1 flex items-center justify-between text-xs text-red-600">
                <span>{row.message}</span>
                {!check(row.file) && (
                  <button type="button" className="underline" onClick={() => upload(row.id, row.file)}>
                    Retry
                  </button>
                )}
              </div>
            ) : (
              <div className="mt-2 h-1 overflow-hidden rounded-full bg-zinc-200 dark:bg-zinc-800">
                <div className="h-full bg-blue-500 transition-[width]" style={{ width: `${row.progress * 100}%` }} />
              </div>
            )}
          </li>
        ))}
      </ul>
    </div>
  );
}

A few choices in that code are deliberate:

  • The zone is a label around a visually hidden input. That gives you click to browse, Tab focus and Enter or Space to open the picker for free, with no role="button" or key handlers to maintain. The has-[:focus-visible] variant draws the focus ring on the label when the hidden input is focused.
  • event.target.value = "" after reading the files lets the person choose the same file again after removing or failing it. Without it, the change event does not fire a second time.
  • The retry button only shows for upload failures, not for files refused by check, because retrying a file that is too large changes nothing.
  • aria-live="polite" on the list means a screen reader announces rows as they are added and finished.

Handling failure properly

Real networks fail in the middle. Treat three cases separately, because they need different messages:

  • Refused before sending (size or type): say exactly what was wrong, with the limit, and offer no retry.
  • Failed during sending (network drop, server error): say the upload failed and offer a retry that restarts the same file.
  • Cancelled by the person: remove the row and call xhr.abort() so the bytes stop leaving the device. Keep the XMLHttpRequest in a ref keyed by row id to do this.

For very large files, split the upload into chunks so a retry resumes instead of starting over. Object storage providers support multipart uploads for this, and the progress callback then sums the chunks.

Reduced motion and small details

If you animate the progress bar or the zone, wrap the movement in motion-safe: Tailwind variants or a prefers-reduced-motion media query, and keep a plain text percentage on the row so the progress never depends on the animation. Show the file size in the row too, because people use it to judge whether an upload is stuck.

Making it feel finished with Nexus UI

The component above is complete and works. What it does not have is any sense of place: the zone is a dashed box and the progress is a bar. If the upload is a moment in your product people notice, like an onboarding step or a media library, two components from Nexus UI start where this guide stops:

  • Pearl Drop is a dropzone with a halftone glass pearl in it. It shows an empty shell of dots while a file is held over the zone, fills with rainbow liquid and a percentage as the newest upload runs, and rises into a tick when it finishes. Files that are too big, of the wrong type or that fail scatter the pearl red and give the reason in the row, with a retry for failures. You pass your own upload function that receives the file and an onProgress callback, so it uses the same send function as above. Pearl Drop is a Pro component.
  • Upload Dropzone has a tray that swallows files, progress rings that become a drawn check, and variants for avatar uploads, an upload queue with pause and cancel, and a CSV drop that fills a table. Upload Dropzone is a Pro component.

Both install with the shadcn CLI, for example npx shadcn@latest add @nexus-labs/pearl-drop, and each component page lists exactly what the install includes. If your uploads are images and you want a preview that builds as the file goes up, read React image upload with a live preview. More form building blocks are in the inputs and controls category.

Frequently asked questions

How do I make a drag and drop file upload in React?

Wrap a hidden file input in a label, handle onDragOver with event.preventDefault() so drops are allowed, read event.dataTransfer.files in onDrop, and pass the same list of files to one function that validates and uploads them. Handling the picker and the drop through the same function keeps behaviour identical.

How do I show upload progress in React?

Use XMLHttpRequest and read xhr.upload.onprogress, which gives loaded and total bytes. Store a number from 0 to 1 per file and render it as a bar and a percentage. The fetch API does not report upload progress in all browsers.

Why does my dropzone flicker when I drag over it?

Child elements fire dragenter and dragleave as the pointer crosses them. Count the events instead of toggling a boolean: add one on dragenter, subtract one on dragleave, and show the active state while the count is above zero. Reset the count to zero in onDrop.

Should I use react-dropzone or build my own?

For a single zone with validation and a list, the code above is short enough to own and has no dependency. A library earns its place when you need directory drops, many edge cases across browsers, or hooks you do not want to maintain. Either way the visual layer, the rows and the progress, is yours to design.

How do I limit file size and type?

Check file.size and file.type in the browser before sending, and say what the limit is in the message. Then check both again on the server, because the browser's checks can be bypassed.

How do I upload multiple files at once?

Put multiple on the input and loop over the dropped or chosen files, giving each its own row, id and progress value. Start each upload independently so one failure does not block the rest, and consider capping how many run at the same time if people drop dozens.

How do I let people upload the same file again?

Reset the input's value after reading its files (event.target.value = ""). The change event only fires when the selection changes, so without the reset, choosing the same file twice does nothing.

Build it with the components from this guide.