Multiple Files Upload to Firebase in React using Ant Design
In this tutorial, we will be using Ant Design and Firebase to create a simple react app that includes uploading multiple files at once to Firebase’s cloud storage. You can checkout the complete code at https://github.com/ajayprazz/react-file-upload.
Ant Design is a popular UI library for React with plethora of easy to use components. It aims to uniform the user interface specs and reduce redundancies and excessive production cost, helping product designers to focus on better user experience.
Firebase is a platform developed by Google for creating mobile and web applications. It allows connecting and sharing data between Android, iOS, and web applications.
Bootstrapping a react app
We will use create-react-app package to create a starter app and then we will install required dependencies.
$ yarn global add create-react-app
$ create-react-app react-file-upload
$ cd react-file-upload
$ yarn add antd firebase react-responsive-masonry
$ yarn start
Create a new firebase project and copy the credentials to .env file.
After this, you can initialize firebase in your react app.
File Upload Form
Create a file upload form using ant design’s Form.
In the above gist, we have used ant design’s Form and Upload component to create a file upload form. We have passed custom props to the Upload to overwrite it’s default functionality.
In the beforeUpload method we have put validation to only allow files with file type “image/jpeg” and “image/png”. And we return false to upload the files manually. In the handleChange method, we check for the status of file returned from beforeUpload and set the fileList into state only if the file status is not error. In the onRemove method, we filter the removed file from the fileList and update the state.
Upload files on form submission
On form submission, we will upload the files to the cloud storage of firebase and save the uploaded files’ details in a firebase collection.
Display the uploaded images
Create another component for displaying the uploaded images. In this component, we will fetch the image list from the firebase collection.
Now we will display the images using react-responsive-masonry.
In the above code excerpt, you can see that a button to delete the selected image has been added. Below css will position the delete button over the image at top-tight position.
To delete the selected image, we will use the path of image saved in the firebase collection.
You can checkout the complete code at https://github.com/ajayprazz/react-file-upload.