In this episode, we tackle the task of enabling drag and drop file uploads using Alpine.js and Livewire. We start by focusing on the area in our UI where users can drop their files. The first step is wiring up the basic Alpine.js data and event handlers to track whether a file is currently being dragged over the drop zone. This gives us the ability to visually indicate the drop area is active, which we do by toggling some Tailwind CSS classes.
Once that's working, we add event handlers for dragover
, dragleave
, and drop
, so our UI can react accordingly. We also add a little debugging helper—a text span showing the current "dropping" state—to confirm things are behaving as expected.
Next, we hook up the actual file drop. When a file is dropped, we extract the file from the event object. We then use Livewire's JavaScript API to manually upload the file, just like when we select a file using an input. We briefly touch on optional callbacks for upload progress, success, and error, but keep things simple for now.
In the end, we make sure our drag and drop upload works just as nicely as our previous click-to-upload feature, but with the added bonus of intuitive file dropping. Now, users can either click the input or simply drag files onto the designated area—super smooth!