In this episode, we tackle how to let users drag and drop files into our uploader, just like they can click to upload. At the start, we point out that right now, dragging a file over just pops it open in the browser, because we haven't put the right handlers in place yet.
So, we go into the uploader component and start wiring up drag-and-drop events. We add a little bit of state to represent whether the user is currently dragging a file over the area (called dropping
), and show its value on the UI for quick feedback. Next, we attach dragover
and dragleave
events so the border color changes when a file is hovering over the drop zone—just for a nice visual indication.
Then, we set up the drop
handler to prevent the browser's default behavior (like opening the file), reset our dropping
state, and call our custom drop handler. We do a quick console log to inspect what actually comes through in the event, and realize we need to account for the difference between dropping and selecting files (since sometimes files are in dataTransfer.files
, and sometimes in event.target.files
). A quick fix later, and it works both ways!
By the end, we've got a drag-and-drop uploader working with visual feedback, and we're ready to move on to combining both drag-and-drop and click select in one smooth handler in the next episode.