In this article, we will talk about creating a file drop feature in React without using any libraries.
The HTML spec provides us with an ondrop event handler for this.
<div ondrop="dropHandler(event);">
Drop files here
</div>We can use the same in React by setting the onDrop attribute (notice the camelCase).
<div onDrop={dropHandler}>
Drop files here
</div>But this is not enough. HTML also supports dragging events and if you try to drag & drop an element, the drag event takes precedence which opens the dropped file by default. Thus we need to disable drag events.
<div onDrop={dropHandler} onDragOver={e => e.preventDefault()}>
Drop files here
</div>With this, we make sure that the file won't open on drop. Now we handle the dropped files.
function App() {
const dropHandler = (e) => {
e.preventDefault();
const files = e.dataTransfer.files;
}
return (
<div onDrop={dropHandler} onDragOver={e => e.preventDefault()}>
Drop files here
</div>
);
}The files are an array of type File.
You can get their file names, file sizes, or read and upload them.

Comments
Nothing yet. Say the first thing.
Sign in to join the conversation.