DEV Community

Cover image for A Drag and Drop File Upload Where Every File Becomes a Box on a Pallet (React + Motion)
Pooja Deliver Website
Pooja Deliver Website

Posted on Edited on

A Drag and Drop File Upload Where Every File Becomes a Box on a Pallet (React + Motion)

Most drag and drop uploads are a dashed rectangle and a list. This one draws the drop zone as a pallet. Every file you drop lands on it as a box, and the box is as tall as the file is big. While a file uploads, its box rises with the progress. A load line next to it shows how much of the pallet's capacity you've used, and a file that would overload it gets turned away with a reason.

It's still a normal file input underneath, so it works with the keyboard, with "click to browse", and with screen readers. Here's how it's built in React with Motion.

The structure

The whole drop zone is a <label> around a visually hidden <input type="file">. That one choice gives you click-to-browse and keyboard support for free: clicking or pressing Enter anywhere on the label opens the file picker.

<label
  onDragOver={(event) => { event.preventDefault(); setIsOver(true); }}
  onDragLeave={() => setIsOver(false)}
  onDrop={drop}
  className="group relative cursor-pointer rounded-2xl bg-sky-950 ring-2 has-focus-visible:ring-sky-300"
>
  <input type="file" multiple accept={accept}
         onChange={(event) => take(event.target.files)}
         className="sr-only" />
  <UploadPallet uploads={uploads} isOver={isOver} />
  <span>{labels.drop}</span>
  <span>{labels.browse}</span>
</label>
🔴 Hot News: deliverui/a drag and drop file upload where every file becomes a box on a pallet react motion b - ประเด็นร้อน 🔴 Hot News: deliverui/a drag and drop file upload where every file becomes a box on a pallet react motion b - ประเด็นร้อน

Two details matter here:

  • event.preventDefault() in onDragOver is what tells the browser this element accepts drops. Without it, onDrop never fires and the browser opens the file instead.
  • has-focus-visible:ring-sky-300 puts the focus ring on the label when the hidden input inside it has keyboard focus. The input is invisible, so the ring has to live on something you can see.

Dropped files and picked files go through the same function:

const take = (files: FileList | null) => setRejected(files ? add([...files]) : []);
const drop = (event: DragEvent) => {
  event.preventDefault();
  setIsOver(false);
  take(event.dataTransfer.files);
};
🔴 Hot News: deliverui/a drag and drop file upload where every file becomes a box on a pallet react motion b - ประเด็นร้อน 🔴 Hot News: deliverui/a drag and drop file upload where every file becomes a box on a pallet react motion b - ประเด็นร้อน

Step 1: a hook that owns the uploads

All the state lives in one hook, useUploads. It holds the list of files, works out how much capacity is used, and starts each upload. The upload itself is a function you pass in, so the component doesn't care whether you send files to S3, your own API or a fake one for a demo:

export type UploadFile = (file: File, onProgress: (progress: number) => void) => Promise<void>;
🔴 Hot News: deliverui/a drag and drop file upload where every file becomes a box on a pallet react motion b - ประเด็นร้อน 🔴 Hot News: deliverui/a drag and drop file upload where every file becomes a box on a pallet react motion b - ประเด็นร้อน

The interesting part is add. It checks every file against the room left before starting anything, and returns the names of the files that didn't fit:

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;
  });
  // ...create an item per accepted file, then start each upload
  return rejected;
};
🔴 Hot News: deliverui/a drag and drop file upload where every file becomes a box on a pallet react motion b - ประเด็นร้อน 🔴 Hot News: deliverui/a drag and drop file upload where every file becomes a box on a pallet react motion b - ประเด็นร้อน

Each accepted file gets an item with progress: 0 and status: "uploading". As the upload reports progress, a small patch helper updates just that item; when the promise resolves it becomes "done", and if it rejects it becomes "failed":

upload(file, (progress) => patch(item.id, { progress }))
  .then(() => patch(item.id, { progress: 1, status: "done" }))
  .catch(() => patch(item.id, { status: "failed" }));
🔴 Hot News: deliverui/a drag and drop file upload where every file becomes a box on a pallet react motion b - ประเด็นร้อน 🔴 Hot News: deliverui/a drag and drop file upload where every file becomes a box on a pallet react motion b - ประเด็นร้อน

Turning files away up front is friendlier than letting them fail halfway. The rejected names go straight into a role="alert" message, so screen reader users hear why a file wasn't taken.

Step 2: how tall is a file?

If box height followed file size directly, one 50 MB video would tower over everything and a 10 KB note would be invisible. So height grows with the logarithm of the size: every doubling adds the same amount.

const KB = 1024;
const MIN_HEIGHT = 6;
const MAX_HEIGHT = 110;
const HEIGHT_PER_DOUBLING = 6.5;

export const boxHeight = (bytes: number) =>
  Math.min(MAX_HEIGHT, MIN_HEIGHT + Math.log2(bytes / KB + 1) * HEIGHT_PER_DOUBLING);
🔴 Hot News: deliverui/a drag and drop file upload where every file becomes a box on a pallet react motion b - ประเด็นร้อน 🔴 Hot News: deliverui/a drag and drop file upload where every file becomes a box on a pallet react motion b - ประเด็นร้อน

A 40 KB note comes out at about 41 units and a 10 MB video at about 92. The video clearly stands taller, but they still fit on the same pallet. That's the main trick of the component: a log scale makes sizes you can compare at a glance.

The box's type comes from the file extension, stencilled on the lid like a shipping crate:

export function fileLabel(name: string): string {
  const extension = name.includes(".") ? name.split(".").pop() : "";
  return (extension || "file").slice(0, 4).toUpperCase();
}
🔴 Hot News: deliverui/a drag and drop file upload where every file becomes a box on a pallet react motion b - ประเด็นร้อน 🔴 Hot News: deliverui/a drag and drop file upload where every file becomes a box on a pallet react motion b - ประเด็นร้อน

Step 3: stacking boxes on the pallet

The pallet has four spots, two by two, and files fill them in turn. For each file, place works out which stack it joins and how high its bottom sits, from the boxes already under it:

const SPOTS = [
  { gx: -52, gy: -52 }, { gx: 52, gy: -52 },
  { gx: -52, gy: 52 },  { gx: 52, gy: 52 },
];

function place(uploads: Upload[]): Placed[] {
  const tops = SPOTS.map(() => PALLET.height);
  return uploads.map((upload, index) => {
    const spot = index % SPOTS.length;
    const height = Math.max(2, boxHeight(upload.size) * (upload.status === "uploading" ? upload.progress : 1));
    const placed = { upload, ...SPOTS[spot], z: tops[spot], height };
    tops[spot] += height + GAP;
    return placed;
  });
}
🔴 Hot News: deliverui/a drag and drop file upload where every file becomes a box on a pallet react motion b - ประเด็นร้อน 🔴 Hot News: deliverui/a drag and drop file upload where every file becomes a box on a pallet react motion b - ประเด็นร้อน

Note the height line: while a file is uploading, its box is only progress times its full height. So the progress bar is the box. Nothing extra to read; the stack simply rises as the bytes arrive.

The pallet is drawn as an isometric SVG, so the boxes are sorted back to front before rendering, otherwise a box in the front row could be painted behind one in the back row.

Step 4: the motion

Each box is a motion.g inside AnimatePresence. A new box drops in from above, and a removed one lifts off:

<motion.g
  key={upload.id}
  initial={isReduced ? false : { opacity: 0, y: -40 }}
  animate={{ opacity: 1, y: 0 }}
  exit={isReduced ? { opacity: 0 } : { opacity: 0, y: -60 }}
  transition={SPRING_SOFT}
>
🔴 Hot News: deliverui/a drag and drop file upload where every file becomes a box on a pallet react motion b - ประเด็นร้อน 🔴 Hot News: deliverui/a drag and drop file upload where every file becomes a box on a pallet react motion b - ประเด็นร้อน

While a file is dragged over the zone, the whole pallet lifts 6 px on a soft spring and the four spots' dashed outlines turn blue: a clear "yes, drop it here". Behind it, a dot-matrix background lights up from the centre, like a switched-off LED board turning on.

Every movement checks usePrefersReducedMotion(). With reduced motion on, boxes simply fade in and out, and the pallet doesn't lift. The upload still works exactly the same.

Step 5: the load line

Next to the pallet, a thin bar shows how full it is. It's a scaleX transform, which is cheap to animate, and it turns amber past 85% so people see the limit coming before they hit it:

<span
  className={cn("block h-full origin-left transition-transform duration-300",
    load > 0.85 ? "bg-amber-400" : "bg-sky-500")}
  style={{ transform: `scaleX(${load})` }}
/>
🔴 Hot News: deliverui/a drag and drop file upload where every file becomes a box on a pallet react motion b - ประเด็นร้อน 🔴 Hot News: deliverui/a drag and drop file upload where every file becomes a box on a pallet react motion b - ประเด็นร้อน

What I'd take from this

  • Wrap a hidden file input in a <label>: click, keyboard and drop all work with one element.
  • Check capacity before uploading and say why a file was turned away.
  • Use a log scale whenever you draw file sizes.
  • Let the progress be the thing itself (the box rising) rather than a separate bar.

The full component, with the list of files, remove buttons and failed state, is free on DeliverWebsite UI: Drag and Drop File Upload

Top comments (0)