Implementing Drag and Drop Upload in React using Supabase
Tags: javascript, beginners, webdev, react
Published: 2023-04-25 11:30:00

## Introduction

In modern web development, implementing drag-and-drop upload functionality has become a common requirement for many applications. Drag and drop allows users to easily upload files by simply dragging them from their local file system and dropping them onto a designated area on the web page.

In this article, we will explore how to implement drag-and-drop upload functionality in a React application using [Supabase](https://supabase.com/). It is a powerful backend-as-a-service platform that allows developers to easily build scalable web applications with serverless functions and a PostgreSQL database. It will be used for storing the data. Along with this, we will also use the [react-drag-drop-files](https://www.npmjs.com/package/react-drag-drop-files) library for creating the UI for uploading.

By the end of this article, you will have a better understanding of how to implement drag-and-drop file uploads in your own React applications using Supabase. Now, let’s get started.

## Supabase Storage

It is one of the core functionality of Supbase for storing data. It can be any media file including images, GIFs, and videos. It is quite easy to upload files to Supabase. There are two types of uploads that Supbase currently offers. Here are those:

- **Standard Upload:** It is the traditional upload where you can upload files. It is recommended for files of smaller sizes. Still, you can upload file of up to 6 GB. But it does not pause and resume while uploading. So, here comes the second type of upload.
- **Resumable Upload:** This is the new thing that was recently launched in [Launch Week 7](https://supabase.com/launch-week). It uses the TUS protocol for creating resumable uploads. This method is a recommended approach for uploading large files that may exceed 6MB in size or in scenarios where network stability is a concern. Additionally, the resumable upload method is useful if you want to display a progress bar to users during the upload process.

Resumable Upload is currently in Beta. But it will available for usage in the next week as per Supabase. So, today we are going to use the Standard Upload for uploading files to the Supabase. Once it is available, I will also demonstrate the use of the resumable uploads using Supabase. 

Now, let’s build the React application.

## Setting Up React

We are going to use CRA for using React. You can use also use other React frameworks. There won’t be much difference. 

Install React with the following command:

```bat
    npx create-react-app standard-upload
```

> Note: To use the above command and further commands, you need to have [nodejs](https://nodejs.org/en/) pre-installed.

Clean up the unnecessary code. Now, it’s time to install the necessary libraries. Here are those:

- **@supabase/supabase-js:** JavaScript library for handling request to Supabase.
- **react-drag-drop-files:** This will handle the drag and drog functionality of our application.

You can install the above libraries with the below command.

```bat
    npm i @supabase/supabase-js react-drag-drop-files
```

## Adding a project to Supabase

First, let’s set up our project on the supabase dashboard. Visit [supabase.com](https://supabase.com/) then click on `Start your project` from the right of the nav bar. This will take you to the sign-in page. Enter your details for sign-in or sign-up as you required. After logging in, you will be redirected to the project page. From here, click on `New project` to create a project. On Create new project page, you will be asked to enter details of your project.

![Screenshot - Create a new project page](https://paper-attachments.dropboxusercontent.com/s_2594E255DCFE7FE59AAA2F62E121C6816FC5D73BEDA3A0965C4AC7D153A45D0C_1670168454105_image.png)


Fill in the details of your project. Enter the project’s name as per your choice. For passwords, you can use the `Generate a password` for generating password. Select the region that is nearest to the user of your project. In the free tier, you can create two projects. After filling the detail, click on `Create new project`. It will take a few minutes to set up the project.

## App.js

Here is the code for the App.js. 

```jsx
    import React, { useState } from "react";
    import { createClient } from "@supabase/supabase-js";
    import { FileUploader } from "react-drag-drop-files";
    
    const fileTypes = ["MP4", "MVI", "AVI", "JPG"];
    
    const supabase = createClient(
      process.env.REACT_APP_SUPABASE_URL,
      process.env.REACT_APP_ANON_KEY
    );
    
    function App() {
      const handleChange = async (file) => {
        const { data, error } = await supabase.storage
          .from("Upload")
          .upload(`./${file.name}`, file);
        if (data) {
          console.log(data);
        } else {
          console.log(error);
        }
      };
    
      return (
        <FileUploader
          handleChange={(file) => handleChange(file)}
          name="video"
          types={fileTypes}
        />
      );
    }
    
    export default App;
```

The code is quite easy to understand. At the top, we have imported the necessary libraries. After this, we have defined a variable for storing the types of files that drag and drop will support. Now, comes the setting up of the supabase client. For this, we need the project URL and anon key. You can get this from `Project Setting` and then `API`.

![Screenshot - API Setting page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6975xzrst8f2qjmldj1y.png)

Now create a `.env` file in the root of your project. Add the details of both as the environment variable.

```env
    REACT_APP_SUPABASE_URL=<Project ULR>
    REACT_APP_ANON_KEY=<anon public>
```

> Note: Prefix the environment variable’s name with NEXT_PUBLIC_. This will be directly loaded to the client.

Now, let’s look at the return statement first.

```jsx
    return (
        <FileUploader
          handleChange={(file) => handleChange(file)}
          name="video"
          types={fileTypes}
        />
    );
```

We have a `FileUploader` component from the `react-drag-drop-files`. You can add more components to make it look even better but this will works fine. 

Let’s look the props of the component.

- **handleChange:** This will trigger when there will be a change such as a user selects or drops files. It will trigger a function with the files that are dropped or selected as an argument. Eventually calling the `handlechange()` function.
- **name:** This is the name give to the file.
- **types:** This includes the array of file extension that is supported.

Now, let’s look at the `handleChange` function.

```jsx
    const handleChange = async (file) => {
        const { data, error } = await supabase.storage
          .from("Upload")
          .upload(`./${file.name}`, file);
        if (data) {
          console.log(data);
        } else {
          console.log(error);
        }
      };
```

We have an asynchronous function here. In this, we are calling the supabase for uploading the file. Before uploading any file, we need to perform the following task in Supabase Project.

- **Creating a bucket:** Bucket is a like a directory in the Supabase where you upload a files. It can have subfolder too. You can create a new bucket, by going to `Storage` and clicking on `New bucket`. Give a proper name and click on `Save` for creating the bucket.
- **Allowing access to upload:** It is initially prohibited to upload files other than Supabase dashboard. For allowing, we have to create a policy for this. Go to `Storage` and then `Policies`. In the Upload section, click on `New Policy`.  This will open a pop up. Click on `For full customization`. Enter a proper name for this policy and select `INSERT` for allowing uploading article. After this, click on `Review` and then `Save` for saving the policy.
![Screenshot - Add policy](https://paper-attachments.dropboxusercontent.com/s_0A310E7C894A710E73DD7B75AD1E0E4E2655DD6CE5432619E0531C8BEF062C5B_1682323979412_image.png)


Now, you are ready to upload media through the Supabase library and APIs. In the supabase method for uploading media there are two arguments.

```jsx
    const { data, error } = await supabase.storage
          .from("Upload")
          .upload(`./${file.name}`, file);
```

The first argument is the file path of the bucket. Inside, the `Upload` bucket you can go further down to save the media. It is the path of the bucket. The second argument is the file. 

## Testing

If you have done all the steps then when you run the React server, you will the below output.

![Screenshot - Our Frontend](https://paper-attachments.dropboxusercontent.com/s_0A310E7C894A710E73DD7B75AD1E0E4E2655DD6CE5432619E0531C8BEF062C5B_1682324950430_image.png)


Now, you will be able to upload files. After successful upload, you will able to see the uploaded file in the bucket on your Supabase dashboard.

## Conclusion

We have implemented the drag and drop file uploads in a React application using Supabase Storage, a powerful cloud-based storage service provided by Supabase. We have seen how easy it is to set up a React application with Supabase and `drag-and-drop-files`  library to create a drag and drop file upload component that enables users to upload files to Supabase Storage with ease.

Supabase Storage is an excellent choice for developers who want to add robust and reliable file upload and sharing functionality to their React applications. With its ease of use, scalability, and advanced features, Supabase Storage provides a comprehensive solution for handling all of your file storage and sharing needs.

I hope this article has helped you in knowing some important features of Supabase i.e, Storage and the drag and drop features. Thank you for reading the article.

---

Drag and drop icons used in cover image is created by <a href="https://www.flaticon.com/free-icons/drag-and-drop" title="drag and drop icons"> Yogi Aprelliyanto - Flaticon</a>