Drag and drop file upload in React, where files stack as boxes (2027)

Build a drag and drop file upload component in React: files become boxes on a pallet as tall as they are large, a dot board that lights under a dragged file, real progress and capacity limits.

6 min read

The real component. Click the picture to open it live and try it before you read how it was built.

File uploads are one of the most searched components, and nearly all look the same: a dashed box. Ours is a pallet: every file you drop becomes a box stacked on it.

As tall as the file is large

Each doubling of a file's size adds a fixed amount of height, so a 10 MB video stands clearly above a 40 KB note without the big ones going off the panel. Each box gets a printed label with its type.

src/registry/interactive/upload/upload-files.ts

// What the pallet does with a file: the label printed on its box, how tall the box stands, and its size in words.
const KB = 1024;
const MB = KB * KB;
const MIN_HEIGHT = 6;
const MAX_HEIGHT = 110;
// Each doubling of a file's size adds this much height, so a 10 MB video stands clearly above a 40 KB note
// without one huge file towering over the rest.
const HEIGHT_PER_DOUBLING = 6.5;

export type UploadStatus = "uploading" | "done" | "failed";

export interface Upload {
  id: string;
  name: string;
  size: number;
  label: string;
  // 0 when it starts, 1 when the upload has finished.
  progress: number;
  status: UploadStatus;
}

// The file's extension, as it would be stencilled on a box: "PDF", "JPG". Files without one get "FILE".
export function fileLabel(name: string): string {
  const extension = name.includes(".") ? name.split(".").pop() : "";
  return (extension || "file").slice(0, 4).toUpperCase();
}

export const boxHeight = (bytes: number) =>
  Math.min(MAX_HEIGHT, MIN_HEIGHT + Math.log2(bytes / KB + 1) * HEIGHT_PER_DOUBLING);

export function formatSize(bytes: number): string {
  if (bytes >= MB) return `${(bytes / MB).toFixed(1)} MB`;
  return `${bytes === 0 ? 0 : Math.max(1, Math.round(bytes / KB))} KB`;
}
How a file becomes a box

Real uploads, real limits

A hook uploads each file and reports progress from 0 to 1, marking failures. A file that would take the pallet over its capacity is refused with a reason, and every box can be taken off again.

src/registry/interactive/upload/use-uploads.ts

"use client";

import { useState } from "react";
import { fileLabel, type Upload } from "./upload-files";

// Uploads a file, reporting progress from 0 to 1 as it goes. Rejecting marks the file as failed.
export type UploadFile = (file: File, onProgress: (progress: number) => void) => Promise<void>;

interface UploadsOptions {
  upload: UploadFile;
  // The pallet's capacity in bytes, across every file on it, and the most files it takes.
  capacity: number;
  maxFiles: number;
}

interface Uploads {
  uploads: Upload[];
  used: number;
  // Adds the files that fit and returns the names of those that did not.
  add: (files: File[]) => string[];
  remove: (id: string) => void;
}

// The files on the pallet and their uploads. A file that would take the pallet over its capacity, or past its
// number of files, is turned away before it starts.
export function useUploads({ upload, capacity, maxFiles }: UploadsOptions): Uploads {
  const [uploads, setUploads] = useState<Upload[]>([]);
  const used = uploads.reduce((sum, item) => sum + item.size, 0);
  const patch = (id: string, change: Partial<Upload>) =>
    setUploads((current) => current.map((item) => (item.id === id ? { ...item, ...change } : item)));

  const add = (files: File[]) => {
    const rejected: string[] = [];
    let room = capacity - used;
    let slots = maxFiles - uploads.length;
    const accepted = files.filter((file) => {
      const fits = file.size <= room && slots > 0;
      if (!fits) return rejected.push(file.name) && false;
      room -= file.size;
      slots -= 1;
      return true;
    });
    const added = accepted.map((file) => ({
      file,
      item: {
        id: `${file.name}-${file.size}-${Date.now()}-${Math.random()}`,
        name: file.name,
        size: file.size,
        label: fileLabel(file.name),
        progress: 0,
        status: "uploading" as const,
      },
    }));
    setUploads((current) => [...current, ...added.map(({ item }) => item)]);
    added.forEach(({ file, item }) => {
      upload(file, (progress) => patch(item.id, { progress }))
        .then(() => patch(item.id, { progress: 1, status: "done" }))
        .catch(() => patch(item.id, { status: "failed" }));
    });
    return rejected;
  };

  return { uploads, used, add, remove: (id) => setUploads((current) => current.filter((item) => item.id !== id)) };
}
The uploads hook

Still a real file input

Click the pallet to browse, use the keyboard, and read each file's name, size and progress in a plain list under it.

More articles