How to use react-dropzone module in ReactJS ?
React-Dropzone module is a simple React hook that is used to create an HTML5-compliant drag-drop zone for n number of files. We can use this module to provide a way for users to drop and drop their multiple files, and then we can handle these files as per the business requirement. We can use the following approach in ReactJS to use the react-dropzone module.
Approach: In the following example, we have used the react-dropzone module to demonstrate how we can use it in our ReactJS application. We have imported the useDropzone which is a wrapper component from the module to get the dropzone property getters which we have used to create the drag ‘n’ drop zone on our Input element. Now whenever user clicks on our sample text: Click to select file or drag-and-drop the file here!! , it will allow the user to select the file, and then we can perform any operation on that file as per business requirement.
Dropzone Props Getters: It helps in creating a drag ‘n’ drop zone as these are the getter functions that return objects with properties that are used for creating drag ‘n’ drop zone. The input properties should be applied to an <input> element whereas the root properties can be applied to any element.
Refs: The getRootProps and getInputProps functions which we get from the Dropzone props accept a custom refKey as one of the parameter attributes. It is useful when the props from getRootProps and getInputPropse function which we try to apply to an element does not expose a reference to the element.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install react-dropzone
Project Structure: It will look like the following.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Step to Run Application: Run the application using the following command from the root directory of the project:
Output: Now open your browser and go to http://localhost:3000/, you will see the following output: