IllustrationsPlays on its own. Click to take over.
Upload
File Dropzone
A drag-and-drop upload area that lifts and glows as files hover over it, then lists each one with an image preview, a live progress bar and a remove button.
Drag files here or browse
Up to 5.0 MB each
Install
Copies the source into components/illustrations/file-dropzone.tsx and installs what it needs.
$ pnpm dlx shadcn@latest add https://makeui.xyz/r/file-dropzone.jsonUsage
app/page.tsx
import { FileDropzone } from "@/components/illustrations/file-dropzone"
export default function Example() {
return (
<FileDropzone
accept="image/*,.pdf"
maxSize={5 * 1024 * 1024}
onFiles={(files) => console.log(files)}
upload={async (file, onProgress) => {
// report progress from 0 to 100 as your upload runs
onProgress(100)
}}
/>
)
}Source
Prefer to copy by hand? It's one file. Requires motion and the shadcn cn helper.
components/illustrations/file-dropzone.tsx
"use client"
import { useCallback, useEffect, useRef, useState } from "react"
import { AnimatePresence, motion, useReducedMotion } from "motion/react"
import { AlertCircle, Check, FileText, UploadCloud, X } from "lucide-react"
import { cn } from "@/lib/utils"
export interface FileDropzoneProps {
/** Same format as the input accept attribute, e.g. "image/*,.pdf". */
accept?: string
/** Largest file allowed, in bytes. Defaults to 5 MB. */
maxSize?: number
multiple?: boolean
/** Called with the files that passed the checks. */
onFiles?: (files: File[]) => void
/** Upload for real. Report progress from 0 to 100. Without it, progress is simulated. */
upload?: (file: File, onProgress: (percent: number) => void) => Promise<void>
/** Plays a fake drag, drop and upload on a loop until someone interacts with it. */
autoPlay?: boolean
className?: string
}
type Item = {
id: string
file: File
progress: number
status: "uploading" | "done" | "error"
error?: string
preview?: string
}
const bytes = (b: number) =>
b < 1024
? `${b} B`
: b < 1048576
? `${Math.round(b / 1024)} KB`
: `${(b / 1048576).toFixed(1)} MB`
const allowed = (file: File, accept?: string) => {
if (!accept) return true
return accept
.split(",")
.map((s) => s.trim().toLowerCase())
.filter(Boolean)
.some((t) =>
t.startsWith(".")
? file.name.toLowerCase().endsWith(t)
: t.endsWith("/*")
? file.type.startsWith(t.slice(0, -1))
: file.type === t,
)
}
// fake files used by autoPlay (tiny blobs with a believable name and size)
const DEMO_FILES = [
{ name: "quarterly-report.pdf", type: "application/pdf", size: 2_400_000 },
{ name: "team-photo.png", type: "image/png", size: 1_100_000 },
{ name: "notes.txt", type: "text/plain", size: 18_000 },
]
const makeDemoFile = (i: number) => {
const d = DEMO_FILES[i % DEMO_FILES.length]
const file = new File(["demo"], d.name, { type: d.type })
Object.defineProperty(file, "size", { value: d.size })
return file
}
export function FileDropzone({
accept,
maxSize = 5 * 1024 * 1024,
multiple = true,
onFiles,
upload,
autoPlay,
className,
}: FileDropzoneProps) {
const reduce = useReducedMotion()
const input = useRef<HTMLInputElement>(null)
const urls = useRef<string[]>([])
const demoIndex = useRef(0)
const [items, setItems] = useState<Item[]>([])
const [over, setOver] = useState(false)
// flips to true as soon as a real person touches the component
const [touched, setTouched] = useState(false)
const patch = useCallback(
(id: string, p: Partial<Item>) =>
setItems((c) => c.map((i) => (i.id === id ? { ...i, ...p } : i))),
[],
)
useEffect(() => () => urls.current.forEach((u) => URL.revokeObjectURL(u)), [])
const run = useCallback(
async (item: Item) => {
try {
if (upload) await upload(item.file, (p) => patch(item.id, { progress: p }))
else
await new Promise<void>((done) => {
let p = 0
const t = setInterval(() => {
p = Math.min(100, p + 8 + Math.random() * 14)
patch(item.id, { progress: p })
if (p >= 100) {
clearInterval(t)
done()
}
}, 160)
})
patch(item.id, { progress: 100, status: "done" })
} catch {
patch(item.id, { status: "error", error: "Upload failed" })
}
},
[upload, patch],
)
const add = (list: File[]) => {
const next: Item[] = (multiple ? list : list.slice(0, 1)).map((file) => {
let error: string | undefined
if (!allowed(file, accept)) error = "File type not allowed"
else if (file.size > maxSize) error = `Too large (max ${bytes(maxSize)})`
const preview =
!error && file.type.startsWith("image/") ? URL.createObjectURL(file) : undefined
if (preview) urls.current.push(preview)
return {
id: `${Date.now()}-${Math.random().toString(36).slice(2)}`,
file,
progress: 0,
status: error ? "error" : "uploading",
error,
preview,
}
})
setItems((c) => (multiple ? [...next, ...c] : next))
onFiles?.(next.filter((i) => i.status !== "error").map((i) => i.file))
next.filter((i) => i.status === "uploading").forEach(run)
}
const remove = (id: string) => {
const gone = items.find((i) => i.id === id)
if (gone?.preview) URL.revokeObjectURL(gone.preview)
setItems((c) => c.filter((i) => i.id !== id))
}
// autoPlay: hover -> drop -> upload -> clear -> repeat, until the user interacts
useEffect(() => {
if (!autoPlay || reduce || touched) return
let cancelled = false
const timers: ReturnType<typeof setTimeout>[] = []
const later = (fn: () => void, ms: number) => {
timers.push(setTimeout(() => !cancelled && fn(), ms))
}
const cycle = () => {
setOver(true) // fake drag enters
later(() => {
setOver(false) // fake drop
add([makeDemoFile(demoIndex.current++)])
}, 1400)
later(() => setItems([]), 5200) // clear the list
later(cycle, 6200) // go again
}
later(cycle, 600)
return () => {
cancelled = true
timers.forEach(clearTimeout)
setOver(false)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [autoPlay, reduce, touched])
// wipe the demo leftovers once a real user takes over
const takeOver = () => {
if (autoPlay && !touched) {
setTouched(true)
setItems([])
setOver(false)
}
}
return (
<div className={cn("w-full max-w-md", className)}>
<div
role="button"
tabIndex={0}
aria-label="Upload files"
onClick={() => {
takeOver()
input.current?.click()
}}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault()
takeOver()
input.current?.click()
}
}}
onDragEnter={(e) => {
e.preventDefault()
takeOver()
setOver(true)
}}
onDragOver={(e) => {
e.preventDefault()
takeOver()
setOver(true)
}}
onDragLeave={(e) => {
if (!e.currentTarget.contains(e.relatedTarget as Node)) setOver(false)
}}
onDrop={(e) => {
e.preventDefault()
takeOver()
setOver(false)
add([...e.dataTransfer.files])
}}
className={cn(
"flex cursor-pointer flex-col items-center gap-3 rounded-3xl border-2 border-dashed px-6 py-9 text-center outline-none transition-colors focus-visible:ring-2 focus-visible:ring-neutral-400/60 focus-visible:ring-offset-2 focus-visible:ring-offset-transparent",
over
? "border-neutral-900 bg-neutral-100 dark:border-neutral-100 dark:bg-neutral-800"
: "border-neutral-300 bg-white hover:border-neutral-400 dark:border-neutral-700 dark:bg-neutral-900 dark:hover:border-neutral-600",
)}
>
<motion.span
animate={over ? { y: -6, scale: 1.12 } : { y: 0, scale: 1 }}
transition={{ type: "spring", stiffness: 400, damping: 18 }}
className={cn(
"grid size-12 place-items-center rounded-2xl transition-colors",
over
? "bg-neutral-900 text-white dark:bg-neutral-100 dark:text-neutral-900"
: "bg-neutral-100 text-neutral-700 dark:bg-neutral-800 dark:text-neutral-200",
)}
>
<UploadCloud className="size-6" />
</motion.span>
<div>
<p className="text-sm font-medium text-neutral-900 dark:text-neutral-100">
{over ? (
"Drop to upload"
) : (
<>
Drag files here or{" "}
<span className="underline underline-offset-4">browse</span>
</>
)}
</p>
<p className="mt-1 text-xs text-neutral-500 dark:text-neutral-400">
Up to {bytes(maxSize)} each
</p>
</div>
<input
ref={input}
type="file"
hidden
accept={accept}
multiple={multiple}
onChange={(e) => {
if (e.target.files) add([...e.target.files])
e.target.value = ""
}}
/>
</div>
<ul className="mt-3 space-y-2">
<AnimatePresence initial={false}>
{items.map((item) => (
<motion.li
key={item.id}
layout
initial={{ opacity: 0, y: -8, scale: 0.98 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, x: 24 }}
transition={{ type: "spring", stiffness: 420, damping: 34 }}
className="flex items-center gap-3 rounded-2xl border border-neutral-200 bg-white p-2.5 dark:border-neutral-800 dark:bg-neutral-900"
>
<span className="grid size-10 shrink-0 place-items-center overflow-hidden rounded-xl bg-neutral-100 text-neutral-500 dark:bg-neutral-800 dark:text-neutral-400">
{item.preview ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={item.preview} alt="" className="size-full object-cover" />
) : (
<FileText className="size-5" />
)}
</span>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium text-neutral-900 dark:text-neutral-100">
{item.file.name}
</p>
{item.status === "error" ? (
<p className="text-xs text-red-600 dark:text-red-400">{item.error}</p>
) : item.status === "uploading" ? (
<div
className="mt-1.5 h-1.5 overflow-hidden rounded-full bg-neutral-200 dark:bg-neutral-800"
role="progressbar"
aria-valuenow={Math.round(item.progress)}
aria-valuemin={0}
aria-valuemax={100}
>
<motion.div
className="h-full rounded-full bg-neutral-900 dark:bg-neutral-100"
animate={{ width: `${item.progress}%` }}
transition={{ duration: 0.2 }}
/>
</div>
) : (
<p className="text-xs text-neutral-500 dark:text-neutral-400">
{bytes(item.file.size)}
</p>
)}
</div>
{item.status === "done" && (
<Check className="size-4 shrink-0 text-neutral-900 dark:text-neutral-100" />
)}
{item.status === "error" && (
<AlertCircle className="size-4 shrink-0 text-red-500" />
)}
{item.status === "uploading" && (
<span className="w-9 text-right text-xs tabular-nums text-neutral-500 dark:text-neutral-400">
{Math.round(item.progress)}%
</span>
)}
<button
type="button"
aria-label={`Remove ${item.file.name}`}
onClick={() => remove(item.id)}
className="grid size-7 shrink-0 place-items-center rounded-lg text-neutral-400 transition-colors hover:bg-neutral-100 hover:text-neutral-900 dark:hover:bg-neutral-800 dark:hover:text-white"
>
<X className="size-4" />
</button>
</motion.li>
))}
</AnimatePresence>
</ul>
</div>
)
}