Drag and Drop using ReactJs

Photo by Jackson So on Unsplash

Drag and Drop using ReactJs

Learn to easily integrate drag and drop file uploads using browser APIs in React.

I was recently trying to implement drag and drop feature for files in my new web application using React.js. While searching about how to get it done, I came across jQuery codes, but not so much about React.
So, I will try to provide the simplest way to achieve this using React.js.

Drag & Drop is an interesting feature and makes your applications much more user friendly.

Setup

For this demo, we are simple going to use create-react-app as it is the simplest way to create a React boilerplate.
Follow these instructions if using create-react-app for the first time
That is it. We will not require any other third-party libraries for this.

File Upload Component

Code

Explanation

This is a very simple component that allows user to select the file or drop it in the browser for upload.

I have called a function on onDragOver to prevent this event from triggering. We want to specifically trigger only the drop event, because we want the file that was dropped by user in this browser window.

We will use the dataTransfer API for obtaining and working with the files that were dropped. This API is available in almost all major browsers (partially supported in IE as well). So, we should not face any compatibility issues.

The dropHandler() obtains the files from the browser API and further calls the uploadFile().
You can update the uploadFile() function as per your backend requirements.

Conclusion

That is it for drag and drop.

As you can see, it is very simple and takes only a few lines of code to implement this feature in React.js

Thank you for reading. Hope you found something you were looking for.