DEV Community

Cover image for How to do image upload with firebase in react.

How to do image upload with firebase in react.

Tallan Groberg on November 30, 2019

As a web developer, giving your user's image uploading capability is a right a passage. I'm writing this article because of how frustrating it was ...
Collapse
 
samuelkarani profile image
Samuel Karani • Edited

refactored updated version:

import React, { useState } from "react";
import firebase from "firebase/compat/app";
import "firebase/compat/storage";

export const storage = firebase.storage();

export default function App() {
  const [file, setFile] = useState(null);
  const [url, setURL] = useState("");

  function handleChange(e) {
    if (e.target.files[0])
        setFile(e.target.files[0]);
  }

  function handleUpload(e) {
    e.preventDefault();
    const path = `/images/${file.name}`;
    const ref = storage.ref(path);
    await ref.put(file);
    const url = await ref.getDownloadURL();
    setURL(url);
    setFile(null);
  }

  return (
    <div>
      <form onSubmit={handleUpload}>
        <input type="file" onChange={handleChange} />
        <button disabled={!file}>upload to firebase</button>
      </form>
      <img src={url} alt="" />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
muhammadanasalvi18 profile image
Anas Alvi

it gives error
storage.ref is not a function

Collapse
 
samuelkarani profile image
Samuel Karani

i've updated the snippet for new firebase >= 9.0

Collapse
 
alaomichael profile image
Michael Alao

Thanks for the tutorial. Please can you guide me on how to use this in a form, an return the image after sumbitting the image to firebase, so that I can use it in a list.

Collapse
 
tallangroberg profile image
Tallan Groberg

I’m sorry for the late response.

The best way I have used this in forms is to have the image upload input outside the form that contains the text
inputs

Then save the imageAsUrl to an object with The text inputs.

So it would look something like this.

Usestate({title: “”, description: “”, imgUrl: “some return from firebase”})

The title and description get saved on a separate form as the img url

I hope that helps and I’m sorry I was so late on the response.

Collapse
 
lydiacha profile image
Lydia Chatziioannou • Edited

Hi Tallan, I'm a complete beginner and I'm afraid I'm not sure what you mean by this comment. I also want to use the uploadImage within a form where I have other text input fields. Is it possible for you to create another tutorial that does exactly that? And also how to display all the data from the form on a different page? My main is problem is... if I'm creating a post with a title, content and then an image how does the image know that it belongs to that specific post with that title and content if the title and content are saved in Firestore and the image is stored in storage? I would appreciate a tutorial on this, there's nothing else out there from what I've seen so far. Thanks!

Thread Thread
 
tallangroberg profile image
Tallan Groberg

Ok, I will see if I can make a part 2 to this tutorial so that it’s easier to see how image uploads fit into the bigger picture with other form data.

This tutorial was designed to be as simple as possible for doing an image upload, but I am seeing the need to show everyone how to use this in a way that you would naturally on a website.

Thanks for the feedback!!

Thread Thread
 
lydiacha profile image
Lydia Chatziioannou • Edited

Amazing, thank you!

Any chance you can create the tutorial this month? ☺️

Collapse
 
alaomichael profile image
Michael Alao

Thank you so much for the reply.
Please how do I restrict user to view only their data in a React ,Redux application? Thank you.

Thread Thread
 
tallangroberg profile image
Tallan Groberg

You will have to make a user auth, I have a tutorial on how to do so with firebase if you want to continue learning more about this kind of stuff.

I don’t know how to do so with redux but it should be fairly similar to react context.

User auth can be very tricky and I would suggest going through my firebase tutorial because that is the easiest way I know how to give users identity on my apps

Thread Thread
 
alaomichael profile image
Michael Alao

Please can you send me the link to your tutorial? Thank you.

Thread Thread
 
tallangroberg profile image
Tallan Groberg

Sure,

Let me know if this works for you!!

Good luck

dev.to/itnext/user-auth-with-fireb...

Collapse
 
francisrod01 profile image
Francis Rodrigues

Hi there, thanks for this tutorial.
Could you suggest the best practice to load a list of posts (with firebase images) in the background?

Collapse
 
tallangroberg profile image
Tallan Groberg

So there are a lot of ways you can do that. You could save the image string to a larger object and then set the background of the div in the style={ backGroundUrl: “imgUrl”}

I don’t know of a good resource for how to do this but if you got my tutorial working you got the hardest part of the process is complete.

Good luck

Collapse
 
francisrod01 profile image
Francis Rodrigues

Thanks for reaching out.
I'm more interested in the part of saving and fetching this data.
Which strategy do you use to do that better?

I'm not sure if it will be a good practice fetching the storage resource every time a user navigates back in a list of records with its storage url.

Thread Thread
 
tallangroberg profile image
Tallan Groberg • Edited

I would suggest multer if you are familiar with node. I'm not sure of a relational database option but building a relational backend would be the very best practice, this article talks about the pros and cons.

You don't technically own your data with firebase unless you save it somewhere else after it's uploaded to firebase and so I personally suggest using multer unless you have some background in relational database building. With these options, you will have more of a say in what happens to the images than what I teach in this tutorial.

Also, It should be a faster API call.

Does that answer your question?

Thread Thread
 
francisrod01 profile image
Francis Rodrigues

Thanks for this interesting package. I'll have a better look at it later.
I was talking about something related to firestore.

You know that Firebase has the Storage service, right? gs://xxxxxx-app.appspot.com

Being more specific, so I've asked if you will upload a file on Firebase Storage service and save its file URL into Firestore or only the file name and loads it every time the user opens the page. That's my question.

Thread Thread
 
tallangroberg profile image
Tallan Groberg

I’m currently working on a tutorial about how to do what you just described. Since I know this tutorial is only good for one small piece of functionality. I’m hoping to release something that ties together using my stuff about firebase specifically.

There is a lot of really good material about firebase on dev.to and the broader web that might be able to get you further on your project.

Thread Thread
 
francisrod01 profile image
Francis Rodrigues

Great!! You can count on me getting beginners/intermediates levels of JavaScript programmers with Firebase questions and bringing it to you. I'm not the only one with such doubts, I can say.

Collapse
 
jailsonpaca profile image
jailsonpaca

Thank You! God Bless you! i am using this tool with React Admin framework.

Collapse
 
lynnknapp profile image
Lynn Knapp

Have I told you lately how awesome you are Tallan, your the best.

Collapse
 
tallangroberg profile image
Tallan Groberg

Your welcome Lynn, your really awesome too!

Collapse
 
bezen13 profile image
BeZen13

Looks great man

Collapse
 
wenzf profile image
wenzf

Great example to make this work. Understandable but reduced to the max. Perfect! Thank you very much for this!

Collapse
 
tallangroberg profile image
Tallan Groberg

Thanks, I’m glad you found it helpful!!!

Collapse
 
trakyrichard profile image
Traky Richard BLM

Thank you for this tutorial it is really rich in knowledge ...

Collapse
 
tallangroberg profile image
Tallan Groberg

You’re welcome.

I’m glad you found it useful

Collapse
 
lucafahrni profile image
Luca Fahrni

Great turtorial, thank you!

Collapse
 
lucafahrni profile image
Luca Fahrni

Saved my ass
Thank you

Collapse
 
bhaktitud profile image
Bhakti Budiman Novanda

Nice! great tutorial, easy to follow. Thanks, this is really helpful!