Javascript required
Skip to content Skip to sidebar Skip to footer

How to Upload All Files at Same Time Dropzone

React Dropzone and file uploads in React banner showing a cloud file upload image next to the React logo.

In this tutorial, nosotros'll learn how to use React Dropzone to create an crawly file uploader. Keep reading to larn more about react-dropzone.

Read part two in the React file upload series: Upload a File from a React Component

To begin, open upward an existing React projection. If you don't have an existing React project that uses the react-dropzone library, generate a new one using Create React App. I'll show you how to do this below.

Call the new projectfile-upload.

I'm also showing you the pick to install Bootstrap, which I'll exist using in the examples throughout this tutorial.

                          

npx create-react-app file-upload cd file-upload npm install --salvage react-dropzone // Optional npm install --salvage bootstrap

A Bones React Dropzone File Picker

We're going to start past building a very uncomplicated file picker using React Dropzone.

As an extra challenge, endeavor to follow this tutorial using React Hooks. If you lot're new to Hooks, I've written a simple introduction to React Hooks.

Jump into App.js  and start by removing the average code in the render role. Subsequently y'all've stripped out this unwanted lawmaking, import theReact Dropzone library at the top of the file, below all of the other imports.

Finally, add the React Dropzone component to the return of the render method, as well every bit an onDrop method above information technology.

Your App.js should look like this:

                          

import React, { Component } from 'react' ; import Dropzone from 'react-dropzone' form App extends Component { onDrop = (acceptedFiles) => { console. log (acceptedFiles) ; } render ( ) { return ( <div className = "text-center mt-5" > <Dropzone onDrop = { this .onDrop} > { ( {getRootProps, getInputProps} ) => ( <div { ... getRootProps ( ) } > <input { ... getInputProps ( ) } / > Click me to upload a file! </div > ) } </Dropzone > </div > ) ; } } export default App;

React Dropzone merely needs one method passed into the onDrop prop to handle files when they're selected.

To go on things simple, we'll name the method the aforementioned equally the prop: onDrop .

Our onDrop method has a unmarried parameter, acceptedFiles, which for the time-being we log out to the console. This is only for testing purposes.

Save the component, open your browser and go to your running React app. Click the text label and a file picker window volition open upwardly! Great! We've got a basic file picker working.

Clicking a file to upload won't practice annihilation just yet. For that to work, we accept to send the file to a server, which we'll cover at a later on date.

Let's continue to explore what else React Dropzone tin practise!

Render Props

Dropzone may wait different to other React components you've seen. This is considering it uses the Return Props technique.

The Render Prop Function is used to change the HTML inside of the Dropzone component, based on the current state of Dropzone.

To demonstrate, let'south add a variable to the Return Prop part called isDragActive. This gives u.s. access to Dropzone's current drag state.

Now that we have access to the isDragActive state, nosotros can alter the text value of the label to show something different when a file is dragged over the component.

                          

<Dropzone onDrop = { this .onDrop} > { ( {getRootProps, getInputProps, isDragActive} ) => ( <div { ... getRootProps ( ) } > <input { ... getInputProps ( ) } / > {isDragActive ? "Drop it like it's hot!" : 'Click me or drag a file to upload!' } </div > ) } </Dropzone >

In the code above, we're writing an inline conditional that checks ifisDragActive is truthful. If it is, write "Drop it similar it's hot", else write, "Click me or drag a file to upload!".

Let's spring back to the browser and see information technology in action.

Allowing Specific Types of File

Currently, our file picker allows usa to pick any blazon of file to upload.

Depending on what you lot're using a file picker for, you may want to allow specific types of files, such equally only .JPG files, or only .XLS and .DOCX files.

To do this, we'll utilize the have prop.

Let'south add together the take prop afterward onDrop  within the Dropzone component announcement, like so:

                          

<Dropzone onDrop = { this .onDrop} accept = "image/png, image/gif" > ... </Dropzone >

File types are written as MIME types, with multiple values separated past a comma. Mozilla has a great resource that gives a full list of MIME types.

Let's improve our file picker user experience by showing a bulletin if the user tries to upload a file blazon that's non accepted.

To practice that, we'll add another return prop chosenisDragRejected. We'll move around the inline conditional logic somewhat to account for this new render prop.

                          

<Dropzone onDrop = { this .onDrop} accept = "prototype/png" > { ( {getRootProps, getInputProps, isDragActive, isDragReject} ) => ( <div { ... getRootProps ( ) } > <input { ... getInputProps ( ) } / > { !isDragActive && 'Click here or drop a file to upload!' } {isDragActive && !isDragReject && "Drop it like it's hot!" } {isDragReject && "File type not accepted, lamentable!" } </div > ) } </Dropzone >

Save the file, hop on back to your browser and try to drag a .JPG file onto the file picker.

A message appears letting the user know that our file picker doesn't take that type of file. Perfect!

Minimum and Maximum File Size

Specifying the minimum and maximum file size is very of import. In a real world file uploader, you lot wouldn't want ane of your users dragging in a 1GB file to upload, and crippling your server.

Luckily we tin can limit the size of the file that's beingness uploaded in React Dropzone through 2 props,minSize and maxSize. Both of these props take a number value specified in bytes.

For your reference, i Megabyte = 1048576 Bytes.

Jump dorsum into your code, and add together the 2 minSize and maxSize props to the Dropzone component, right underneath the take prop.

                          

<Dropzone onDrop = { this .onDrop} accept = "image/png" minSize = { 0 } maxSize = { 5242880 } > ... </Dropzone >

We're accepting a file with a maximum size of 5MB and under in the instance above.

Let's add some more code to our file input component that checks the maximum file size and displays an error bulletin if the file existence uploaded is larger.

                          

return ( ) { const maxSize = 1048576 ; return ( <div className = "text-center mt-five" > <Dropzone onDrop = { this .onDrop} accept = "image/png" minSize = { 0 } maxSize = {maxSize} > { ( {getRootProps, getInputProps, isDragActive, isDragReject, rejectedFiles} ) => { const isFileTooLarge = rejectedFiles.length > 0 && rejectedFiles[ 0 ] .size > maxSize; return ( <div { ... getRootProps ( ) } > <input { ... getInputProps ( ) } / > { !isDragActive && 'Click here or driblet a file to upload!' } {isDragActive && !isDragReject && "Drop it like it'southward hot!" } {isDragReject && "File type not accepted, sorry!" } {isFileTooLarge && ( <div className = "text-danger mt-two" > File is besides big. </div > ) } </div > ) } } </Dropzone > </div > ) ; }

It might look like we've added a lot, but actually it's less than ten lines.

  • At the acme of the render method, nosotros declare a new const called maxSize and set information technology to 1MB.
  • Reference this new maxSize variable in the maxSize prop within Dropzone.
  • We add another render prop to Dropzone called rejectedFiles
  • Straight underneath the render prop function within Dropzone, we declare another const called isFileTooLarge, which gets the first file from the rejectedFiles array prop, and checks to see if the size is greater than our maxSize variable.
  • Finally, nosotros're writing an inline provisional that checks if isFileTooLarge is true, and renders 'File is too big.' in blood-red.

Let'due south see information technology in action!

Multiple Files

The terminal characteristic of React Dropzone that we'll cover is the ability to upload multiple files.

This 1 is fairly simple, equally we're non adding any lawmaking within the return prop part.

Only add themultiple prop to the React Dropzone component declaration, like and so:

                          

<Dropzone onDrop = { this .onDrop} accept = "image/png" minSize = { 0 } maxSize = {maxSize} multiple > ... </Dropzone >

React Dropzone using Hooks

Since writing this tutorial React Hooks have been officially released, and the react-dropzone library has been updated to include a custom useDropzone Hook.

Therefore, I've re-written the whole App.js as a functional component using the useDropzone custom hook provided by react dropzone:

                          

import React, { useCallback } from 'react' ; import { useDropzone } from 'react-dropzone' const App = ( ) => { const maxSize = 1048576 ; const onDrop = useCallback (acceptedFiles => { console. log (acceptedFiles) ; } , [ ] ) ; const { isDragActive, getRootProps, getInputProps, isDragReject, acceptedFiles, rejectedFiles } = useDropzone ( { onDrop, accept: 'image/png' , minSize: 0 , maxSize, } ) ; const isFileTooLarge = rejectedFiles.length > 0 && rejectedFiles[ 0 ] .size > maxSize; return ( <div className = "container text-heart mt-5" > <div { ... getRootProps ( ) } > <input { ... getInputProps ( ) } /> { !isDragActive && 'Click here or drop a file to upload!' } {isDragActive && !isDragReject && "Driblet it like information technology'due south hot!" } {isDragReject && "File type not accepted, sad!" } {isFileTooLarge && ( <div className = "text-danger mt-2" > File is too large. </div > ) } </div > </div > ) ; } ; export default App;

Showing a List of Accustomed Files

1 nice bear on we could add together to our react dropzone component is to encounter a list of accustomed files earlier nosotros upload them. It's a dainty bit of UX that goes a long fashion to adding to the experience.

The useDropzone Hook provides us a variable, a cceptedFiles, which is an array of File objects. Nosotros could map through that array and display a list of all the files that are ready to be uploaded:

                          

... <ul className = "list-grouping mt-2" > {acceptedFiles.length > 0 && acceptedFiles. map (acceptedFile => ( <li className = "list-group-item listing-group-item-success" > {acceptedFile.name} </li > ) ) } </ul > ...

A react app, built using the react dropzone library showing someone dragging a file and dropping it on a react dropzone area.

Wrapping Upwardly

There you lot have information technology! A simple file picker component congenital using React Dropzone. If you enjoyed the tutorial or ran into any issues, don't forget to go out a comment beneath.

keithanho1952.blogspot.com

Source: https://upmostly.com/tutorials/react-dropzone-file-uploads-react