Build the upload first, then make it pretty. In React, the real work is done by the browser’s File, FormData, object URL, drag and drop, and fetch APIs. shadcn/ui makes the buttons, cards, alerts, and progress states feel clean without a fight. The browser File API is built for reading file names, sizes, types, and preview data [source: MDN].
TLDR: Use a hidden <input type="file">, then wrap it with shadcn/ui components like Button, Card, and Progress. Store selected files in React state. Preview images with URL.createObjectURL(). For example, a support form can allow 3 screenshots, cap each at 5 MB, and turn a painful 6 message email chain into a simple 2 step upload.
Start with the basic plan
A file upload looks fancy. It is not magic.
You need four simple parts:
- A file picker with
input type="file". - A nice trigger, like a shadcn/ui
Button. - A preview area, usually inside a
Card. - An upload action using
FormDataandfetch.
The annoying bit is styling. Native file inputs still look like they were sent here from 2009. Honestly, it feels like the browser wants you to suffer for 12 extra minutes. So hide the input. Click it with a nice button. Done.
Install the pieces you need
If you already use shadcn/ui, add a few components:
npx shadcn@latest add button card progress alert label
You can use more later. But start small. Small code is happy code.
Create the upload component
Here is a simple React file uploader. It supports multiple files, previews images, checks size, and uploads with fetch.
import { useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { Alert, AlertDescription } from "@/components/ui/alert";
const MAX_SIZE = 5 * 1024 * 1024;
export function FileUploader() {
const inputRef = useRef(null);
const [files, setFiles] = useState([]);
const [error, setError] = useState("");
const [progress, setProgress] = useState(0);
function handleFiles(fileList) {
const picked = Array.from(fileList);
const tooBig = picked.find(file => file.size > MAX_SIZE);
if (tooBig) {
setError("One file is too large. Max size is 5 MB.");
return;
}
setError("");
setFiles(picked);
}
async function uploadFiles() {
const formData = new FormData();
files.forEach(file => {
formData.append("files", file);
});
setProgress(40);
await fetch("/api/upload", {
method: "POST",
body: formData,
});
setProgress(100);
}
return (
<Card className="max-w-xl">
<CardContent className="space-y-4 pt-6">
<input
ref={inputRef}
type="file"
multiple
className="hidden"
onChange={e => handleFiles(e.target.files)}
/>
<Button onClick={() => inputRef.current?.click()}>
Pick files
</Button>
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{files.map(file => (
<div key={file.name} className="text-sm">
<strong>{file.name}</strong>
<span> {(file.size / 1024 / 1024).toFixed(2)} MB</span>
</div>
))}
<Progress value={progress} />
<Button disabled={!files.length} onClick={uploadFiles}>
Upload
</Button>
</CardContent>
</Card>
);
}
This is plain and practical. It does not try to be clever. Good.
Add image previews
People like seeing what they picked. Especially with photos, avatars, receipts, or memes that should not be in a work app. Add previews with object URLs.
{files.map(file => {
const isImage = file.type.startsWith("image/");
const previewUrl = isImage ? URL.createObjectURL(file) : null;
return (
<div key={file.name} className="rounded border p-3">
{previewUrl && (
<img
src={previewUrl}
alt={file.name}
className="mb-2 h-24 rounded object-cover"
/>
)}
<p><strong>{file.name}</strong></p>
</div>
);
})}
One warning. Object URLs should be cleaned up in larger apps. If users add and remove lots of files, use URL.revokeObjectURL(). Memory leaks are not cute.
Support drag and drop
Clicking is fine. Dragging feels better. Add a drop zone around your card.
function handleDrop(event) {
event.preventDefault();
handleFiles(event.dataTransfer.files);
}
function handleDragOver(event) {
event.preventDefault();
}
Then use it like this:
<div
onDrop={handleDrop}
onDragOver={handleDragOver}
className="rounded-lg border border-dashed p-8 text-center"
>
Drop files here or click the button.
</div>
The catch is that drag and drop can feel broken if you forget preventDefault(). The browser may open the file instead. That is fun for nobody.
Show real upload progress
fetch is great. But it does not give easy upload progress in every common setup. If you need exact progress, use XMLHttpRequest. Yes, it is old. Yes, it still works.
const xhr = new XMLHttpRequest();
xhr.upload.onprogress = event => {
if (event.lengthComputable) {
const percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
};
xhr.open("POST", "/api/upload");
xhr.send(formData);
Use fetch for simple uploads. Use XMLHttpRequest when a real progress bar matters.
Validate before upload
Never trust the client. Still, client checks help users fix mistakes fast.
- Check size. Example: max
5 MB. - Check type. Allow images, PDFs, or docs only.
- Check count. Example: max
3 files. - Check names. Show clear file names before upload.
Server checks still matter. A user can bypass your React code. The client is for comfort. The server is for safety.
Keep the experience friendly
A good upload flow talks to the user. Use shadcn/ui alerts for errors. Use progress for waiting. Use disabled buttons when nothing is selected. Use plain words.
Say “Max file size is 5 MB”. Do not say “Invalid payload constraint exceeded”. Nobody wants that. Not even the backend team.
Here is the final recipe:
- Hide the native file input.
- Trigger it with a shadcn/ui
Button. - Store files in React state.
- Preview images with object URLs.
- Send files with
FormData. - Show progress, errors, and success states.
That is it. You now have file uploads that feel modern, clear, and less annoying. Your users pick a file. They see it. They upload it. Nobody has to ask, “Did it work?”