How to upload an image to firebase storage & save that images’ URL in firestore database in React+Firebase

Shubham Metkar
2 min readNov 26, 2022

--

image source: https://css-tricks.com/wp-content/uploads/2017/06/reactfirebase.png

So recently I was stuck in a small implementation while working with registration form in react & firebase where I wanted to save the uploaded images’ URL in a document of firestore database.
Let’s explore it in this article.

TL;DR
Let’s see our demo in action:

Demonstration

Implementation:

It’s assumed that you’ve boilerplate react app ready with you & also have some basic pre-requisite known about how to create firebase account, new project and a new web app inside it & enabling firestore database and storage from it. We’ll be making use of some libraries to make our life easier which are:

Then make sure you’ve a firebase-config.js file in your root directory i.e inside root of /src folder which looks like this:

Now we’ll export some entities such as app ,auth & storage object and will make use of them in our app.js.

Let’s jump into the core of our main file, we first had a material-ui input element and wrapped it inside a handleSubmit event handler.
Now we’ll see closely how we’re able to save uploaded images’ URL in firestore database to make it globally accessible:

  • STEP 1: storing uploaded image in storage:
    First we created a reference to our image storage named storageRef & passed it to uploadBytesResumable function which accepts this reference and the file needed to upload. For more detailed procedure, refer this.
  • STEP 2: storing this image as an URL in firestore database:
    We created a generic reference to our firestore named collectionRef which takes 3 parameters which are db object, collection name and last is document id(which can be auto-generated or something meaningful incontext to your application, here for the sake of simplicity I’ve hardcoded document id.
    Then we have a uploadTask.on() event, which has a callback function inside which we used promise based getDownloadURL function and got the images’ url in downloadURL variable.
    Now comes the important part we simply pushed this url in our document using updateDoc function.(Note that we could’ve made use of setDoc function but we used updateDoc because we wanted to update some fields of a document without overwriting the entire document.

Conclusion:

That’s it, if you’ve any dobuts or need any further assistance hit me up, thanks for reading 😃

--

--