How to create a Custom Drag & Drop Hook in React!🔥

How to create a Custom Drag & Drop Hook in React!🔥

 25
 3
 5 minutes

Hello guys!! Recently, while working on a project, I came accross a situation where I needed to implement Drag and drop feature for uploading files to the server. But, the problem was that, the (component) file in which I was working was already large, so I wanted to somehow separate the drag and drop logic from my component logic, and I ended up creating a hook.<br />

In this article, I want to share exactly, how I created a custom hook for drag and drop feature. <br>

So, let's build it!! 🔥

Let me show you the end result of what we will be building. ezgif-4-7bd93a6caeeb.gif

Initialize a React Project.

After the project is initialized, let's create a form in App.js.


In the App.css, make the following changes to make it look beautiful, or you can do your own custom styling!


Now, let's create the hook

Create a folder called hooks and inside it create a file "useDragAndDrop.ts". In this file, we will create the necessary state and methods for the drag and drop feature.

First we will create two states dragOver and fileDropError. DragOver will determine if the file is being dragged over our label element, and fileDropError will contain the error message if there is any error after dropping the file. In this case, we want an image, so the fileDropError will likely store error messages related to file not being of the type image.


Next, we will create two function onDragOver() and onDragLeave(), this will the toggle the state of dragOver, and then will return all the states and method.


The final code will look like this.


And that's it for this file. Now, let's come back to App.js and implement our hook.

Import useDragAndDrop from the hooks folder. and then destructure all the values from our hook. We will also need a file state to store the file.


Now let's specify the onDragOver and onDragLeave methods on our label like this. Please note that the onDrop function here is not related to our hook, but will be called when the file is dropped. We will create this function in the App.js itself.

We also add some conditional styling and conditional rendering. This will just change the border styling and the text inside the label once the file is being dragged over the label. (Look in the picture) below


Screenshot from 2021-08-19 12-54-10.png

Now, we will create the onDrop() and fileSelect() function for setting the file state after the file is dropped or selected.


Mention the onChange handler on the input element.

Also, we need to conditionally render any error we have.


Final App.js looks like this.


And That's it we have successfully created custom Drag & Drop hook!

I hope you liked the article and gained some knowledge as well. All the codes used are there in the github repository mentioned below. Github Repo - https://github.com/shaan71845/react-custom-drag-and-drop-hook