Lesson 5 of 8
File Uploads & Drag-and-Drop
File uploads require handling the file input (always uncontrolled), providing preview, tracking upload progress, and integrating with a backend via FormData. The drag-and-drop API makes this feel modern - react-dropzone handles the complexity.
File Upload with Preview & Progress
import { useState, useCallback } from 'react';
import { useDropzone } from 'react-dropzone';
interface UploadedFile {
file: File;
preview: string;
progress: number;
status: 'pending' | 'uploading' | 'done' | 'error';
url?: string;
error?: string;
}
function FileUploader({ onUploadComplete }: { onUploadComplete: (urls: string[]) => void }) {
const [files, setFiles] = useState<UploadedFile[]>([]);
const onDrop = useCallback((acceptedFiles: File[], rejectedFiles: unknown[]) => {
const newFiles: UploadedFile[] = acceptedFiles.map(file => ({
file,
preview: file.type.startsWith('image/')
? URL.createObjectURL(file)
: '',
progress: 0,
status: 'pending',
}));
setFiles(prev => [...prev, ...newFiles]);
}, []);
const { getRootProps, getInputProps, isDragActive } = useDropzone({
onDrop,
accept: { 'image/*': ['.jpg', '.jpeg', '.png', '.webp'], 'application/pdf': ['.pdf'] },
maxSize: 10 * 1024 * 1024, // 10MB
maxFiles: 5,
});
async function uploadFile(uploadedFile: UploadedFile) {
setFiles(prev => prev.map(f =>
f === uploadedFile ? { ...f, status: 'uploading' } : f
));
const formData = new FormData();
formData.append('file', uploadedFile.file);
try {
const xhr = new XMLHttpRequest();
// Track upload progress
xhr.upload.onprogress = (e) => {
if (!e.lengthComputable) return;
const progress = Math.round((e.loaded / e.total) * 100);
setFiles(prev => prev.map(f =>
f === uploadedFile ? { ...f, progress } : f
));
};
const url = await new Promise<string>((resolve, reject) => {
xhr.onload = () => {
if (xhr.status === 200) resolve(JSON.parse(xhr.responseText).url);
else reject(new Error(`Upload failed: ${xhr.status}`));
};
xhr.onerror = () => reject(new Error('Network error'));
xhr.open('POST', '/api/upload');
xhr.send(formData);
});
setFiles(prev => prev.map(f =>
f === uploadedFile ? { ...f, status: 'done', progress: 100, url } : f
));
} catch (err) {
setFiles(prev => prev.map(f =>
f === uploadedFile ? { ...f, status: 'error', error: (err as Error).message } : f
));
}
}
// Cleanup object URLs on unmount to avoid memory leaks
useEffect(() => () => {
files.forEach(f => { if (f.preview) URL.revokeObjectURL(f.preview); });
}, [files]);
return (
<div>
<div
{...getRootProps()}
style={{
border: `2px dashed ${isDragActive ? '#229c6b' : '#475569'}`,
borderRadius: 12,
padding: 40,
textAlign: 'center',
cursor: 'pointer',
background: isDragActive ? 'rgba(59, 130, 246, 0.05)' : 'transparent',
transition: 'all 0.2s',
}}
>
<input {...getInputProps()} />
<p style={{ fontSize: 16, color: isDragActive ? '#229c6b' : '#94a3b8', margin: 0 }}>
{isDragActive ? '๐ Drop the files here...' : '๐ Drag & drop files here, or click to select'}
</p>
<p style={{ fontSize: 12, color: '#64748b', marginTop: 8 }}>
Images and PDFs up to 10MB ยท Max 5 files
</p>
</div>
{files.length > 0 && (
<div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 8 }}>
{files.map((f, i) => (
<div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, background: '#1e293b', borderRadius: 8, padding: 12 }}>
{f.preview && <img src={f.preview} alt="" style={{ width: 40, height: 40, borderRadius: 4, objectFit: 'cover' }} />}
<div style={{ flex: 1 }}>
<p style={{ margin: 0, fontSize: 13, fontWeight: 600 }}>{f.file.name}</p>
<p style={{ margin: 0, fontSize: 11, color: '#64748b' }}>{(f.file.size / 1024).toFixed(0)} KB</p>
{f.status === 'uploading' && (
<div style={{ background: '#334155', borderRadius: 999, height: 4, marginTop: 4 }}>
<div style={{ background: '#229c6b', height: '100%', borderRadius: 999, width: `${f.progress}%`, transition: 'width 0.2s' }} />
</div>
)}
</div>
<span style={{ fontSize: 12, color: f.status === 'done' ? '#4ade80' : f.status === 'error' ? '#f87171' : '#94a3b8' }}>
{f.status === 'done' ? 'โ Done' : f.status === 'error' ? 'โ Error' : f.status === 'uploading' ? `${f.progress}%` : '-'}
</span>
{f.status === 'pending' && (
<button onClick={() => uploadFile(f)} style={{ background: '#229c6b', border: 'none', color: 'white', padding: '4px 12px', borderRadius: 6, cursor: 'pointer', fontSize: 12 }}>
Upload
</button>
)}
</div>
))}
</div>
)}
</div>
);
}Tip
Tip
Practice File Uploads DragandDrop in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and flow for File Uploads & Drag-and-Drop
Practice Task
Note
Practice Task - (1) Write a working example of File Uploads DragandDrop from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with File Uploads DragandDrop is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Finished this lesson?