Dropzone custom review file in line năm 2024

Hi! Today I want to tell you about a topic that had to deal with some time ago, and I didn’t find an easy and comprehensive solution for it, but after sometime searching e trying different things I figured it out, the title says it all.

In one of my projects I had to add the possibility for the client to send multiple images and relate then to a product since it was an online store. The problem was that every time the client sent multiple images, the default image of the product was the first one, and sometimes the first image wasn’t the best to describe the product, so i started digging into the dropzone documentation to find a solution, adding some kind of button, after a while I found that the best solution was to add a custom button within the dropzone preview template. So i started reading how people have done it on Stack Overflow, but i didn’ t find any solution that fulfill my needs, so i built one on my own.

First create the dropzone and specify the previewTemplate.

If you read the code, bellow the dz-remove button which is the button used to remove the image within the dropzone, i added and button with dz-set-default class that will be our buttun the will set an image to be the default.

Lets give it some style.

Now lets handle the upload and add images to the the dropzone.

If you want to add images to the dropzone, bellow the dropzone initialization add this code add adapt it to your own situation. Long story short what i am doing is getting all images of the product object and then loop throw them and add then to the dropzone instance, after adding we are checking if the image is the default one and set the start accordingly.

To handle the upload of each image we will listen to the complete event of dropzone, add the image to the product object and then attatch the id of the image to the previewTemplate, for us to know what image is when we want to set as default image.

Right now the result will be somethimg like this:

Now we need to specify the action of the default button. We will do that with the following code:

In this lines of code we are removing the filled start of the current default image and giving that class to the new default image, in the middle of the code you can do some server requests if you want to.

The uploading of files is a common feature found in most web applications, and drag and drop functionality has become a convenient way to achieve this. To implement this feature in a React application, the react-dropzone module is a popular choice due to its rich set of features and customization options that can be tailored to suit individual needs.

This article aims to provide an in-depth understanding of the react-dropzone module, explore various methods of utilizing its functionality to implement drag and drop, and provide examples of customizing its behavior.

React Dropzone Module: An Introduction

React Dropzone, also known as react-dropzone, is a React module that allows for easy creation of drag-and-drop functionality within a React application. This module simplifies the user's file uploading experience, enabling them to drag files from their file explorer and drop them into the application for immediate upload. With a plethora of customization options, React Dropzone is a feature-rich module. Users can restrict the types of files that can be uploaded, as well as upload multiple files simultaneously, among other capabilities.

How to Install, and Modeling a Basic React Dropzone File Picker

To add the react-dropzone module to an application, we can utilize the following command.

npm install react-dropzone

This module is ideal for any application that involves file uploading, such as a university entrance application website, a job application site, or a post uploading platform. Our initial step is to construct a basic file picker with React Dropzone.

Initially, we should import the React Dropzone library below all other imports in the file. Following this, we can include the React Dropzone component in the render method's return statement, as well as an onDrop method above it. The resulting code should resemble the following:

import React, { Component } from 'react';
import Dropzone from 'react-dropzone'
class App extends Component {
  onDrop = (acceptedFiles) => {
    console.log(acceptedFiles);
  }
  render() {
    return (
      
{({getRootProps, getInputProps}) => (
Click me to upload a file!
)}
); } } export default App;

Enter fullscreen mode Exit fullscreen mode

React Dropzone requires only one method to be passed into the onDrop prop to handle file selection. To maintain simplicity, we will name the method onDrop to match the prop name.

The onDrop method has a single parameter, acceptedFiles, which we will currently log to the console for testing purposes. After saving the component, we can open our browser and navigate to our running React app.

Clicking the text label will open a file picker window, which is a great start! However, selecting a file to upload will not have any effect at this time. To make file uploads functional, we need to send the file to a server, which will be covered in a future tutorial.

Render Props

React Dropzone's appearance may appear distinct from other React components you've encountered because it employs the Render Props technique.

The Render Prop Function modifies the HTML within the Dropzone component based on its current state.

To demonstrate this concept, we'll add a variable to the Render Prop function named isDragActive. This variable grants us access to the Dropzone component's current drag state.

With the isDragActive state available, we can alter the text value of the label to display something distinct when a file is dragged over the component.


  {({getRootProps, getInputProps, isDragActive}) => (
    
{isDragActive ? "Drop it like it's hot!" : 'Click me or drag a file to upload!'}
)}

Enter fullscreen mode Exit fullscreen mode

The code snippet mentioned above demonstrates an inline conditional that examines whether isDragActive is true or not. If it is true, the text "Drop it like it's hot" is displayed, and if it is false, the text "Click me or drag a file to upload!" is shown.

To Allow Specific Types of Files

At present, our file selector permits us to choose any file type to upload.

However, depending on the purpose of the file picker, we may want to restrict the selection to specific file types, such as only .JPG files, or only .XLS and .DOCX files.

To achieve this, we can use the accept prop and add it after onDrop within the Dropzone component declaration.


...

Enter fullscreen mode Exit fullscreen mode

File types are represented as MIME types, and Mozilla provides a comprehensive list of MIME types.

To enhance the user experience of our file picker, we can display a message when the user attempts to upload a file type that is not accepted.

We can accomplish this by adding another render prop called isDragRejected and modifying the inline conditional logic accordingly.


  {({getRootProps, getInputProps, isDragActive, isDragReject}) => (
    
{!isDragActive && 'Click here or drop a file to upload!'} {isDragActive && !isDragReject && "Drop it like it's hot!"} {isDragReject && "File type not accepted, sorry!"}
)}

Enter fullscreen mode Exit fullscreen mode

Finally, we can save the file and test it by attempting to drag a .JPG file onto the file picker in the browser. When we do so, a message is displayed indicating that our file picker does not accept that type of file.

The Highest and Lowest File Size

Setting a limit on the file size is crucial to prevent users from uploading excessively large files and overloading your server.

React Dropzone offers two props, minSize and maxSize, which allow you to set the minimum and maximum file size in bytes.

To specify a maximum file size of 5MB or less, add the minSize and maxSize props to the Dropzone component below the accept prop.

App.js

  ...

Enter fullscreen mode Exit fullscreen mode

To enhance the user experience, let's add some code to our file input component that verifies the maximum file size and displays an error message if the uploaded file exceeds the limit.

render() {
  const maxSize = 1048576;
  return (
    
{({getRootProps, getInputProps, isDragActive, isDragReject, rejectedFiles}) => { const isFileTooLarge = rejectedFiles.length > 0 && rejectedFiles[0].size > maxSize; return (
{!isDragActive && 'Click here or drop a file to upload!'} {isDragActive && !isDragReject && "Drop it like it's hot!"} {isDragReject && "File type not accepted, sorry!"} {isFileTooLarge && (
File is too large.
)}
)} }
); }

Enter fullscreen mode Exit fullscreen mode

Despite the appearance of a significant amount of code, it is only a few lines (usually less than 10).

Here are the instructions:

  • We create a constant named "maxSize" and set its value to 1MB at the beginning of the render method.
  • We use the "maxSize" constant in the "maxSize" prop of the Dropzone component.
  • We add a new render prop called "rejectedFiles" to the Dropzone component.
  • After the render prop function in the Dropzone component, we define another constant called "isFileTooLarge". It retrieves the first file from the "rejectedFiles" array and checks if its size is greater than the "maxSize" constant we defined earlier.
  • We then use a conditional statement to check if "isFileTooLarge" is true and display the message "File is too large." in red.

Let's test the functionality in the browser!

More than One File in Action!

The final feature we will discuss about React Dropzone is the capability to upload multiple files. It is a straightforward process and does not involve any changes to the render prop function. To enable this feature, we just need to add the "multiple" prop to the React Dropzone component declaration.


  ...

Enter fullscreen mode Exit fullscreen mode

How to Use Hooks in React Dropzone

The release of React Hooks and the updated version of react-dropzone library with the custom useDropzone Hook has prompted a rewrite of the entire component as a functional one. This involves 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 (
    
{!isDragActive && 'Click here or drop a file to upload!'} {isDragActive && !isDragReject && "Drop it like it's hot!"} {isDragReject && "File type not accepted, sorry!"} {isFileTooLarge && (
File is too large.
)}
); }; export default App;

Enter fullscreen mode Exit fullscreen mode

How to Show a List of Accepted Files

The availability of React Hooks and the updated version of react-dropzone library, which includes a custom useDropzone Hook, has resulted in a complete rewrite of the component as a functional one. This rewrite entails utilizing the useDropzone custom hook provided by react-dropzone.

...
    {acceptedFiles.length > 0 && acceptedFiles.map(acceptedFile => (
  • {acceptedFile.name}
  • ))}
...

Enter fullscreen mode Exit fullscreen mode

Conclusion

To sum up, react-dropzone is a widely used React module that enables drag and drop functionality in web applications. This package provides many customization options, including the ability to limit the size of uploaded files and allowing specific file types to upload. Additionally, the package offers the ability to upload multiple files and display a list of uploaded files easily. With react-dropzone, we don't have to rely on the HTML drag and drop API, which was previously the most common way to upload files using drag and drop.

How do I access Dropzone files?

To access all files in the dropzone, use myDropzone. files . If you do not need a dropzone anymore, just call . disable() on the object.

How do I upload multiple files to Dropzone?

Dropzone Multiple File Upload.

Multiple simultaneous file upload;.

Works out of the box;.

Upload files through a web screen or a REST URL;.

Drag & Drop;.

Click to Upload;.

Upload without submit (ajax submit);.

Launches an event every time a file has been successfully uploaded;.

How do you style a Dropzone?

If you want to theme your Dropzone to look fully customized, in most cases you can simply replace the preview HTML template, adapt your CSS, and maybe create a few additional event listeners.

How do I use Dropzone options?

The easiest way to use dropzone is by creating a form element with the class dropzone :.

class="dropzone".

id="my-awesome-dropzone">

.