Drag and Drop a File feature in React JS

React JSJavascript LibraryFront End Technology

Drag and Drop interfaces enable web applications to allow users to drag and drop files on a web page. In this article, we will see how an application can accept one or more files that are dragged from the underlying platform's file manager and dropped on a web page. Here, we will be using the react-dropzone package. Let's get started.

Example

First of all, create a React project −

npx create-react-app newproject

Go to the project directory −

cd newproject

Now download and install the react-dropzone package −

npm i --save react-dropzone

We will use this library to add a droppable area inside our React element's area. This is used to add a file selection area too.

In this example, we will add the name of a file in a list using drag-and-drag feature. Insert the following lines of code in App.js

import React from "react";
import { useDropzone } from "react-dropzone";
function Basic(props) {
   const { acceptedFiles, getRootProps, getInputProps } =
useDropzone();

   const files = acceptedFiles.map((file) => (
      <li key={file.path}>
         {file.path} - {file.size} bytes
      </li>
   ));
   return (
   <section className="container">
      <div {...getRootProps({ className: "dropzone" })}>
         <input
            {...getInputProps()}
            style={{ backgroundColor: "black", color: "white" }}
         />
         <br />
         <p>Drag 'n' drop some files here, or click to select files</p>
      </div>
      <aside>
         <h4>Files</h4>
         <ul>{files}</ul>
      </aside>
      </section>
   );
}
export default App

function App() {
   return <Basic />;
}

Explanation

We have created three variables −

  • The first variable stores all the file details,

  • The second variable defines the area where this drag-and-drop feature will work, and

  • The third variable makes the input field droppable.

Output

On execution, it will produce the following output −

You can drag-and-drop files onto this page from any folder. It will display the file name along with its size. Also, you can use the "Choose files" button to open a folder location and select a file.

raja
Published on 29-Sep-2021 08:34:42
Advertisements