DEV Community

Cover image for Implementing Drag & Drop File Uploads in React Without External Libraries
HexShift
HexShift

Posted on • Edited on

3 1 1

Implementing Drag & Drop File Uploads in React Without External Libraries

Implementing Drag & Drop File Uploads in React Without External Libraries

Adding drag and drop file upload functionality in React doesn’t require large libraries like React DnD or Dropzone. With just a bit of native browser API and clean React state management, you can build it from scratch. Here’s a step-by-step guide to implementing drag & drop file uploads using only native APIs and React hooks.

1. Set Up Your React Component

Create a new functional component and set up basic state using useState to store the dropped files:

import React, { useState } from "react";

function FileUploader() {
  const [files, setFiles] = useState([]);

  const handleDrop = (e) => {
    e.preventDefault();
    const droppedFiles = Array.from(e.dataTransfer.files);
    setFiles(droppedFiles);
  };

  const handleDragOver = (e) => {
    e.preventDefault();
  };

  return (
    <div
      onDrop={handleDrop}
      onDragOver={handleDragOver}
      style={{
        border: "2px dashed #ccc",
        padding: "20px",
        textAlign: "center",
        borderRadius: "10px",
      }}
    >
      <p>Drag and drop files here</p>
      <ul>
        {files.map((file, index) => (
          <li key={index}>{file.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default FileUploader;

2. Add Visual Feedback

Users love feedback when they’re dragging files over a drop zone. Add a new isDragging state and some conditional styling to indicate when the user is hovering over the drop zone:

const [isDragging, setIsDragging] = useState(false);

const handleDragEnter = () => setIsDragging(true);
const handleDragLeave = () => setIsDragging(false);

<div
  onDrop={handleDrop}
  onDragOver={handleDragOver}
  onDragEnter={handleDragEnter}
  onDragLeave={handleDragLeave}
  style={{
    border: "2px dashed #ccc",
    padding: "20px",
    textAlign: "center",
    borderRadius: "10px",
    backgroundColor: isDragging ? "#f0f8ff" : "#fff",
  }}
>

3. Filter File Types (Optional)

If you want to restrict uploads to certain file types (e.g., images), filter the dropped files before setting them to state:

const handleDrop = (e) => {
  e.preventDefault();
  const droppedFiles = Array.from(e.dataTransfer.files);
  const imageFiles = droppedFiles.filter(file => file.type.startsWith("image/"));
  setFiles(imageFiles);
};

4. Upload to Server (Optional)

To actually upload the files to your backend or storage service, add an upload handler with fetch or axios:

const uploadFiles = async () => {
  const formData = new FormData();
  files.forEach(file => formData.append("files", file));

  const res = await fetch("/api/upload", {
    method: "POST",
    body: formData,
  });

  if (res.ok) {
    alert("Upload successful!");
  } else {
    alert("Upload failed.");
  }
};

Add a button to trigger the upload:

<button onClick={uploadFiles}>Upload Files</button>

Conclusion

Creating a drag and drop upload component in React doesn’t require a lot of overhead. Native browser APIs provide everything you need to deliver a responsive and intuitive experience with minimal code. Keep it lightweight, style it cleanly, and give your users the interaction they expect — no extra libraries required. Ready to become a master? Buy my Patreon article '100 Tips to Make You an Expert at Incorporating Drag & Drop File Uploads in React' now!

For a much more extensive guide on getting the most out of React portals, check out my full 24-page PDF file on Gumroad. It's available for just $10:

Using React Portals Like a Pro.

Now check out - Phoenix LiveView: The Pro’s Guide to Scalable Interfaces and UI Patterns. Whether you’re building collaborative apps, integrating APIs, or orchestrating systems across multiple languages, this guide will help you use Phoenix as the real-time command center your architecture deserves.

Top comments (0)