How to drag and drop files in React
Implementing drag and drop file upload provides an intuitive user experience for React applications handling file uploads. As the creator of CoreUI with over 11 years of React development experience since 2014, I’ve built drag and drop interfaces in countless file management systems. The most effective solution is to use HTML5 drag and drop events with state to manage drag status and uploaded files. This approach works natively in all modern browsers without external libraries.
Use HTML5 drag and drop events to implement file drag and drop in React.
const [isDragging, setIsDragging] = useState(false)
const [files, setFiles] = useState([])
const handleDragEnter = (e) => {
e.preventDefault()
e.stopPropagation()
setIsDragging(true)
}
const handleDragLeave = (e) => {
e.preventDefault()
e.stopPropagation()
setIsDragging(false)
}
const handleDragOver = (e) => {
e.preventDefault()
e.stopPropagation()
}
const handleDrop = (e) => {
e.preventDefault()
e.stopPropagation()
setIsDragging(false)
const droppedFiles = Array.from(e.dataTransfer.files)
setFiles(droppedFiles)
console.log('Files dropped:', droppedFiles)
}
return (
<div
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
style={{
border: `2px dashed ${isDragging ? '#007bff' : '#ccc'}`,
padding: '40px',
textAlign: 'center',
backgroundColor: isDragging ? '#f0f8ff' : 'white',
borderRadius: '8px'
}}
>
<p>{isDragging ? 'Drop files here' : 'Drag and drop files here'}</p>
{files.length > 0 && (
<ul>
{files.map((file, index) => (
<li key={index}>{file.name} ({file.size} bytes)</li>
))}
</ul>
)}
</div>
)
The drag event handlers prevent default browser behavior to enable custom drop handling. The isDragging state provides visual feedback when files are being dragged over the drop zone. The handleDrop function accesses dropped files through e.dataTransfer.files and converts the FileList to an array. Preventing default on all drag events is crucial to avoid the browser opening dropped files.
Best Practice Note
This is the same drag and drop pattern we use in CoreUI React file upload components. Add file type and size validation in the handleDrop function before accepting files. For better UX, highlight the drop zone border and background when dragging, and provide visual feedback for invalid file types.



