日本語

How to Create a File Drop Zone in React

​​React​Accessibility,Drag and Drop API,File API,Playwright,TypeScript

You can create a drop zone for files from your computer by attaching four handlers to a div: onDragEnter, onDragOver, onDragLeave, and onDrop. The key points are calling preventDefault() in dragover to tell the browser that the drop is allowed, and reading the dropped files from dataTransfer.files in drop.

Add highlighting while a drag is in progress, handle drops that land outside the zone, and include a button for people who don't use a mouse, and you have a component you can actually use. In this article I build a DropZone component that accepts only images and PDFs, and I verify each part step by step.

Note

The test environment was Ubuntu 24.04, Node.js 22.22.0, and Chromium 153. I used react / react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx with tsc, transpiled it with esbuild, and drove Chromium with Playwright. Dragging files in from the OS was reproduced with Input.dispatchDragEvent from the Chrome DevTools Protocol, not with a real mouse. I did not test Firefox, Safari, smartphones, or dragging folders.

A dashed box turns light blue when a file is dragged over it. When the file is released, the accepted file appears in a list. On the second attempt, a text file is removed
Dragging a file into the box changes its color. Releasing it shows the number of accepted files and the list (the drag was reproduced with a Chrome DevTools Protocol command)

What to do in each of the four events

When a file from the OS is dragged into the browser, dragstart and dragend do not fire. As explained in MDN's article on file drag and drop, you detect that something has entered with dragenter and dragleave. On the drop zone side, you use the following four events.

Event When it fires What this component does
dragenter When the pointer enters the zone or an element inside it Increments the enter count by 1 and highlights the zone
dragover Repeatedly, while the pointer is over the zone Calls preventDefault() to signal that a drop is allowed
dragleave When the pointer leaves the zone or an element inside it Decrements the enter count by 1, and removes the highlight when it reaches 0
drop When the mouse button is released over the zone Calls preventDefault() and receives the files

In React, each of these can be passed to a div as a handler that receives a DragEvent. You read information about what is being dragged from e.dataTransfer.

The whole DropZone component

DropZone receives the accepted types (accept) and a function that gets the accepted files (onFiles) as props.

tsx
import { useEffect, useRef, useState, type ChangeEvent, type DragEvent } from 'react';

type Props = {
  // Accepted types. Both wildcard forms like 'image/*' and exact forms like 'application/pdf' work
  accept: string[];
  onFiles: (files: File[]) => void;
};

// Whether the dragged item contains files. The contents cannot be read until drop, but types can be read
function hasFiles(e: DragEvent | globalThis.DragEvent) {
  return e.dataTransfer?.types.includes('Files') ?? false;
}

function isAccepted(file: File, accept: string[]) {
  return accept.some((type) =>
    type.endsWith('/*') ? file.type.startsWith(type.slice(0, -1)) : file.type === type,
  );
}

export function DropZone({ accept, onFiles }: Props) {
  const [dragging, setDragging] = useState(false);
  const [message, setMessage] = useState('');
  // dragenter and dragleave fire each time the pointer enters or leaves a child element, so count how many times we have entered
  const depth = useRef(0);
  const inputRef = useRef<HTMLInputElement>(null);

  // If a file is dropped outside the zone, stop the browser from opening it
  useEffect(() => {
    const onDragOver = (e: globalThis.DragEvent) => {
      if (!hasFiles(e)) return;
      e.preventDefault();
      e.dataTransfer!.dropEffect = 'none';
    };
    const onDrop = (e: globalThis.DragEvent) => {
      if (hasFiles(e)) e.preventDefault();
    };
    window.addEventListener('dragover', onDragOver);
    window.addEventListener('drop', onDrop);
    return () => {
      window.removeEventListener('dragover', onDragOver);
      window.removeEventListener('drop', onDrop);
    };
  }, []);

  const receive = (list: FileList) => {
    const files = [...list];
    const accepted = files.filter((file) => isAccepted(file, accept));
    const rejected = files.length - accepted.length;
    setMessage(
      `${accepted.length}件を受け付けました` +
        (rejected > 0 ? `(対応していない種類の${rejected}件を除きました)` : ''),
    );
    if (accepted.length > 0) onFiles(accepted);
  };

  const handleDragEnter = (e: DragEvent<HTMLDivElement>) => {
    if (!hasFiles(e)) return;
    depth.current += 1;
    setDragging(true);
  };

  const handleDragOver = (e: DragEvent<HTMLDivElement>) => {
    if (!hasFiles(e)) return;
    e.preventDefault(); // Without this, drop never fires
    e.stopPropagation(); // Stop window's dragover from setting dropEffect to none
    e.dataTransfer.dropEffect = 'copy';
  };

  const handleDragLeave = (e: DragEvent<HTMLDivElement>) => {
    if (!hasFiles(e)) return;
    depth.current -= 1;
    if (depth.current === 0) setDragging(false);
  };

  const handleDrop = (e: DragEvent<HTMLDivElement>) => {
    if (!hasFiles(e)) return;
    e.preventDefault();
    depth.current = 0;
    setDragging(false);
    receive(e.dataTransfer.files);
  };

  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) receive(e.target.files);
    e.target.value = ''; // So that change fires even when the same file is picked again
  };

  return (
    <div
      className={dragging ? 'dropzone dragging' : 'dropzone'}
      onDragEnter={handleDragEnter}
      onDragOver={handleDragOver}
      onDragLeave={handleDragLeave}
      onDrop={handleDrop}
    >
      <p>ここにファイルをドラッグ</p>
      <button type="button" onClick={() => inputRef.current?.click()}>
        ファイルを選ぶ
      </button>
      <input
        ref={inputRef}
        type="file"
        multiple
        accept={accept.join(',')}
        hidden
        onChange={handleChange}
      />
      <p role="status">{message}</p>
    </div>
  );
}

The caller passes it like this. In the tests, I listed the name, type, and size of each received file below the zone.

tsx
<DropZone accept={['image/*', 'application/pdf']} onFiles={add} />

Without preventDefault in dragover, drop never fires

Ordinary elements do not accept a dragged item even when it is dropped on them. According to MDN's explanation of drag operations, only an element whose dragover has been canceled with preventDefault() becomes a valid drop target. The React reference for onDragOver also says that you must call e.preventDefault() here to make an element droppable.

To check this, I made a version that does not call preventDefault() in onDragOver, and dropped a file on the zone. The drop event never fired.

text
--- 4. Version that does not call preventDefault in dragover ---
drop イベントの回数: 0

You also call preventDefault() in drop. MDN explains that a drop is considered successful only when drop is canceled.

The file names cannot be read while dragging

You can read the contents of dataTransfer.files on the drop target only during drop. According to MDN's description of DataTransfer.files, the list is empty during a drag. In my test, I dragged cat.png and memo.pdf together and printed the values readable at each event. The results matched.

text
dragenter: types=["Files"] files.length=0 items=["file:image/png","file:application/pdf"] names=[]
dragover: types=["Files"] files.length=0 items=["file:image/png","file:application/pdf"] names=[]
drop: types=["Files"] files.length=2 items=["file:image/png","file:application/pdf"] names=["cat.png","memo.pdf"]

dataTransfer.types can be read during a drag. According to MDN's description of DataTransfer.types, when files are included, the list contains the string Files. hasFiles in DropZone checks for this, so the zone ignores drags that are not files. When I dragged text data instead of a file, the zone was not highlighted, and dropping it accepted nothing.

In the test, dataTransfer.items also exposed the types (such as image/png) during the drag. If you want to show "this type cannot be dropped" during the drag, you can check the type in items and set dropEffect to none, as in the MDN example for file drag and drop. In this article's component, I checked the types all together after drop.

dragleave fires when moving over child elements

The zone contains text and a button. When the pointer moves from the text inside the zone onto the button, the button receives dragenter, and the element the pointer just left receives dragleave. Both events bubble up to the zone's div. If you remove the highlight as soon as dragleave arrives, the highlight disappears even though the pointer is still inside the zone.

text
--- 3. Version that clears the highlight immediately on dragleave ---
枠の中の文字の上: 強調=true status="" 一覧=[] URL=http://localhost:5173/?variant=naive-leave
枠の中のボタンの上: 強調=false status="" 一覧=[] URL=http://localhost:5173/?variant=naive-leave

So DropZone keeps a count (depth) in a useRef: it increments on dragenter and decrements on dragleave. Only when the count returns to 0 does it decide that the pointer has left the zone. Since this value is not used for rendering, it is a ref rather than state. As described in the useRef reference, changing ref.current does not cause a re-render. When I ran the same movement against DropZone, the highlight stayed on while the pointer was over the button, and it cleared only when the pointer left the zone.

text
--- 2. Highlighting and receiving drops in DropZone ---
枠の外: 強調=false status="" 一覧=[] URL=http://localhost:5173/
枠の中の文字の上: 強調=true status="" 一覧=[] URL=http://localhost:5173/
枠の中のボタンの上: 強調=true status="" 一覧=[] URL=http://localhost:5173/
枠の外に戻る: 強調=false status="" 一覧=[] URL=http://localhost:5173/
もう一度ボタンの上: 強調=true status="" 一覧=[] URL=http://localhost:5173/
ボタンの上で落とす: 強調=false status="2件を受け付けました(対応していない種類の1件を除きました)" 一覧=["cat.png(image/png、120バイト)","memo.pdf(application/pdf、15バイト)"] URL=http://localhost:5173/

When the mouse button is released, no dragleave fires. In the test, the number of dragleave events received inside the zone stayed at 2 before and after dropping over the button. That is why handleDrop resets the count to 0 and removes the highlight.

For a drag that is canceled partway, MDN's explanation of drag operations says that dragleave is always fired when the drag is canceled. My test method could not reproduce a cancel. Even when I sent the cancel command (dragCancel) through the Chrome DevTools Protocol, no dragleave fired and the highlight stayed on. I have not verified what happens when Esc is pressed during a real mouse drag.

Preventing the browser from opening a file dropped outside the zone

According to MDN's article on file drag and drop, if a file is dropped outside a drop target, the browser may open or download the file. To prevent this, DropZone attaches dragover and drop listeners to window inside useEffect. For file drags, it calls preventDefault() in dragover and sets dropEffect to none, which tells the browser that a drop here is not allowed.

In this environment, when I dropped a file outside the zone with a version that had no window listeners, the page did not navigate to another page. I did not verify the browser's own behavior of opening the file. What I did verify is that the DropZone listener works: dragover outside the zone is canceled, and dropEffect becomes none.

text
--- 5. Version that does not stop it at window, dropping outside the frame ---
ページの移動: なし
window に届いたイベント: ["dragover(preventDefault 済み=false、dropEffect=copy)"]
--- 6. Dropping outside the frame in DropZone ---
ページの移動: なし
window に届いたイベント: ["dragover(preventDefault 済み=true、dropEffect=none)"]

There is a problem if the window listener changes dropEffect to none while the pointer is inside the zone. To avoid this, handleDragOver calls e.stopPropagation(). Since React 17, React attaches its event listeners to the root element where React renders, rather than to document (the event delegation change in the React 17 release candidate announcement). When e.stopPropagation() is called, the event stops at that root element and does not reach window. In React 19, which this article uses, I dropped a file inside the zone afterward. window did not receive dragover, only drop arrived, and the file was accepted.

text
window に届いたイベント: ["drop(preventDefault 済み=true、dropEffect=copy)"]
枠の中に落としたあと: 強調=false status="1件を受け付けました" 一覧=["cat.png(image/png、120バイト)"] URL=http://localhost:5173/

Because stopPropagation() is called, any other handler that listens for dragover on window will also stop receiving the event while the pointer is inside the zone. If you have such a handler, change it to follow MDN's example and check with contains inside the window listener whether the event target is inside the zone.

Verify accepted types yourself

The accept attribute on input only narrows the candidates in the file picker. MDN's explanation of input type="file" notes that it does not verify the types of selected files. Because accept is an attribute of input, it has no effect on files dropped onto a div. So DropZone runs both drops and button selections through isAccepted inside receive.

When I dropped cat.png, memo.pdf, and notes.txt together, only notes.txt was removed, and the status message reported "2 files accepted; 1 file of an unsupported type was removed."

Warning

file.type is determined by the file extension, not by the file's contents. According to MDN's explanation of Blob.type, a PNG file renamed to .txt becomes text/plain, and for an unfamiliar extension the value is an empty string. Treat the browser-side check as guidance for the user, and also verify the file type on the server that receives the upload.

Also allow selection with a button for keyboard and other users

Some people cannot use drag and drop, and others prefer not to. The MDN example also lets users choose files from an input for these cases. DropZone includes an <input type="file"> hidden with hidden, and the "Choose file" button opens it with inputRef.current?.click().

In the test, I moved focus to the button with Tab and pressed Enter, and the file picker opened. Because I added multiple, the picker allows selecting several files. Files chosen this way go to the same receive function as dropped files.

The line e.target.value = '' at the end of handleChange makes sure change fires even when the same file is picked again. With an input whose value is not reset, selecting the same cat.png twice fired change only once. DropZone accepted it both times, and two entries appeared in the list.

text
--- 10. Selecting the same file twice with an input whose value is not reset to empty ---
1回目に cat.png を選んだあとの change の回数: 1
2回目に cat.png を選んだあとの change の回数: 1

For sending the received files to a server and showing progress, see my earlier article on uploading files in React with a progress display.

Point

A drop zone works by calling preventDefault() in dragover and reading dataTransfer.files in drop. During a drag, check whether types includes Files. Track the enter count to know when to remove the highlight. Stop misdirected drops outside the zone with a window listener, and verify file types yourself after receiving them. Adding a button for file selection lets keyboard users operate the zone in the same way.

​Posted by 86