How to use react-dropzone module in ReactJS ?
Last Updated :
23 Nov, 2023
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.
Prerequisites:
Approach:
The integration of the “react-dropzone” module into a ReactJS application. The “useDropzone” wrapper component is imported to obtain dropzone property getters. These getters are applied to an Input element, creating a drag-and-drop zone. Clicking on the text “Click to select the file or drag-and-drop the file here!!” prompts the user to select a file, enabling subsequent operations based on business requirements.
Steps to Create the 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:
cd foldername
Step 3: Install the required module using the following command:
npm install react-dropzone
Project Structure:
Project Structure
The update dependencies in package.json file will look like:
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-dropzone": "^14.2.3",,
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}
Example: Now write down the following code in the App.js file
App.js
import React, { useCallback } from 'react'
import { useDropzone } from 'react-dropzone'
export default function App() {
const onDrop = useCallback(acceptedFiles => {
alert(acceptedFiles[0].name)
console.log( "Now you can do anything with" +
" this file as per your requirement" )
}, [])
const { getInputProps, getRootProps } = useDropzone({ onDrop })
return (
<div style={{ display: 'block' , width: 700, padding: 30 }}>
<h4>React-Dropzone Module Demo</h4>
<div {...getRootProps()}>
<input {...getInputProps()} />
<p>Click to select file or
drag-and-drop the file here!!</p>
</div>
</div>
);
}
|
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...