Categories
React Answers

How to upload image with React dropzone?

Spread the love

Sometimes, we want to upload image with React dropzone.

In this article, we’ll look at how to upload image with React dropzone.

How to upload image with React dropzone?

To upload image with React dropzone, we can define a drop event handler function and upload the selected file inside the handler.

For instance, we write:

import React, { useCallback } from "react";
import { useDropzone } from "react-dropzone";

export default function App() {
  const onDrop = useCallback(async (acceptedFiles) => {
    const formData = new FormData();
    const [file] = acceptedFiles;
    formData.append("file", file);

    await fetch("https://httpbin.org/post", {
      method: "POST",
      body: formData
    });
  }, []);
  const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });

  return (
    <div {...getRootProps()}>
      <input {...getInputProps()} />
      {isDragActive ? (
        <p>Drop the files here ...</p>
      ) : (
        <p>Drag 'n' drop some files here, or click to select files</p>
      )}
    </div>
  );
}

We define the onDrop function with the useCallback hook.

We pass in an async function that gets the file from acceptedFiles.

Then we create a new form data object with the FormData constructor.

And we call append with the file as the value a form data entry.

Then we call fetch with the URL and an object with the body set to formData to do the upload.

Next, we call the useDropzone hook to return an object with a function of properties that we either call or render.

We call getRootProps and getInputProps and spread the returned object as props.

And we get whether we’re dragging a file to the drop zone with isDragActive.

Now when we drop a file into the drop zone, a request should be made to do the upload.

Conclusion

To upload image with React dropzone, we can define a drop event handler function and upload the selected file inside the handler.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *