Welcome folks today in this blog post we will be using the react-files
library to drag and drop
multiple files in gallery with validation
in browser using javascript. All the full source code
of the application is shown below.
Get Started
In order to get started you need to make a new react.js
app using the below command as shown below
npx create-react-app sampleapp
cd sampleapp
And after that you need to install the below library
using the below command as shown below
npm i react-files
And after that you will see the below directory
structure of the react.js app as shown below
Embeding Drag and Drop Widget
Now we can modify the App.js
file and copy paste the following code
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
import React, { useState } from 'react' import Files from 'react-files' export default function App () { const [files,setFiles] = useState([]) const handleChange = (newFiles) => { console.log(files) setFiles(prevFiles => [...prevFiles, ...newFiles]) } const handleError = (error, file) => { alert(error.code + error.message) console.log('error code ' + error.code + ': ' + error.message) } return ( <div className="files"> <Files className='files-dropzone' onChange={handleChange} onError={handleError} accepts={['image/png', '.pdf', 'audio/*']} multiple maxFileSize={10000000} minFileSize={0} clickable> {files.length === 0 && ( <div>Drop files here</div> )} {files.length > 0 && ( <div className="files-gallery"> {files.map(file => ( <img style={{width:"200px",height:"200px"}} key={file.id} className="files-gallery-item" src={file.preview.url} /> ))} </div> )} </Files> </div> ) } |
As you can see we are importing the react-files
library at the top and then we are declaring the hooks
variable for storing the files
selected by the user. And then we are passing different validation filters
to the drag and drop
widget controlling the size
and extension
of files that the user can select. And then we are using the map
operator to loop through all the selected
images and showing the live
preview of it inside the gallery as shown below