DEV Community

Klemen Slavič
Klemen Slavič

Posted on

Want to be able to drag files into a web app? Got ya covered.

It's 2023. We all know how annoying it is when a web app wants us to provide a file but makes it cumbersome by only letting you do that by clicking on Ye Olde <input type=file>. All modern browsers have supported a much better way to do that for a while now, and this library makes it a snap to use them in any environment, vanilla or framework.

The Setup

Install @krofdrakula/drop in your dependencies or use as your module import.

Create some HTML in your page:

<div id="drop_target" style="padding:40px;border:1px solid blue;">
  Drop files here.
Enter fullscreen mode Exit fullscreen mode

In your JS, grab that element and pass it to the create function:

import { create } from '@krofdrakula/drop';

const dropTarget = document.body.getElementById("drop_target");

create(dropTarget, {
  onDrop: (files) => console.log(files)
Enter fullscreen mode Exit fullscreen mode

Open the page in a browser, open dev tools and drag a file into the element you created.

In React-like Components

The create() function returns a cleanup function that can be used in conjuction with useRef and useEffect to correctly set it up:

import { useRef, useEffect } from 'react';
import { create } from '@krofdrakula/drop';

const MyComponent = ({ onDrop }) => {
  const dropTarget = useRef();

  useEffect(() => {
    // you must return the returned function for it to be
    // able to clean up event handlers
    return create(dropTarget.current, { onDrop });
  }, [dropTarget.current, onDrop]);

  return <div ref={dropTarget}>Drop files here.</div>
Enter fullscreen mode Exit fullscreen mode

Handy Features

create takes a number of options that let you configure the behaviour of the control:

  • it exposes various event handlers that let you control the element when the pointer hovers over it when dragging files or without;
  • it lets you specify parser functions that allow you to convert files dropped onto the element before passing them to the onDrop handler;
  • it uses the native file picker when clicking on the element by default.

Check out the demo site to see it in action, or read the README for the full Monty.

All of this in a package that fits any application's download limits.


This package currently does everything I needed it to for the cases I knew it should handle. If you decide to try this out and hit a problem, let me know!

Top comments (0)