DEV Community

Clint Maruti
Clint Maruti

Posted on

Simple Firebase Image Uploader/Display with ReactJs

As a newbie in react, I spent a chunk of time looking for a simple and well elaborated tutorial on uploading an image to firebase. Most of the tutorials I found were displeasing. This left me frustrated and utterly dissapointed. I decided to seek help from a friend who later became my mentor later on. Without further a do, let's dive in, hoping it will help someone out there.

Now, I assume that you atleast have the basic knowledge on react and firebase, if not I recommend this book - A Firebase in React Tutorial for Beginners [2019] by ROBIN WIERUCH. On getting this book, you will also be added to a slack channel for react where you can collaborate with other react developers.

Setting Up Firebase

Go to firebase.com and sign in with your gmail account. Click on get started to create your project. In case you are wondering which location to select, just pick any, it really doesn't matter. Finally you have your firebase project ready.

Next, we are going to add firebase to our a web app. Click on the add web app icon. Register your web app by giving it a nickname. On the next slide, copy your web app Firebase configurations:-

// Your web app's Firebase configuration
  var firebaseConfig = {
    apiKey: "AIzaSyC_O7nBCsvepKmcmswxabDyPDafIy8ta60",
    authDomain: "react-tutorial-7bf4c.firebaseapp.com",
    databaseURL: "https://react-tutorial-7bf4c.firebaseio.com",
    projectId: "react-tutorial-7bf4c",
    storageBucket: "",
    messagingSenderId: "145638556257",
    appId: "1:145638556257:web:dce1f6b880d2f342"
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
Enter fullscreen mode Exit fullscreen mode

N/B: These are my configurations, don't copy paste it instead use yours.

Next, we will make a few changes to our firebase configurations from the web console. On the left panel, Develop, go to storage. Here, we will make a default bucket and make some changes to the storage rules to allow read and write of data to our newly created bucket. Click get started and walk through the setup. Again don't mind about the region, just click next and done.

Select the rules tab, locate this line

allow read, write: if request.auth != null;

Change it to

allow read, write: if true;

Creating Our React Application

The application we are going to build with React and Firebase will be set up with Facebook's official React boilerplate project called create-react-app. You can install it globally on the command line once, after which it becomes available whenever you need it.

npm install -g create-react-app

After the installation, set up your project with it on the command line whereas the name for the project is up to you. Afterward, navigate on the command line into the project:

create-react-app react-image-uploader
cd react-image-uploader

This will generate the necessary react files and install dependencies to run your app. Next we will add our firebase dependencies to our app. Run npm i firebase --save but if you are using yarn you can run yarn add firebase.

Fire up your editor and open your project. I prefer using vsCode. Inside your scr folder, add another folder and name it Firebase. Go ahead to add index.js file inside the Firebase folder. This will hold our firebase configurations.

Inside scr\Firebase\index.js, import firebase from firebase/app module. Then storage from firebase. Next, paste your configurations. Store firebase storage function inside a variable and then export firebase and the storage function. Your file should now look like this:-

import firebase from "firebase/app";
import "firebase/storage";

// Your web app's Firebase configuration
const firebaseConfig = {
  apiKey: "AIzaSyBZ4xQXULFhh51CV7VPgNnuOEZy3jsVaQQ",
  authDomain: "react-drawer-1.firebaseapp.com",
  databaseURL: "https://react-drawer-1.firebaseio.com",
  projectId: "react-drawer-1",
  storageBucket: "react-drawer-1.appspot.com",
  messagingSenderId: "177095687889",
  appId: "1:177095687889:web:05c8c913de0ba493"
};

// Initialize Firebase

firebase.initializeApp(firebaseConfig);```



<b>Image Upload Component</b>

On your `scr` folder create another folder and name it `ImageUpload` then create `index.js` file inside it. Paste this code inside the file.



```javascript
import React, { Component } from "react";
import storage from "../Firebase/index";

class ImageUpload extends Component {
  constructor(props) {
    super(props);
    this.state = {
      image: null,
      url: "",
      progress: 0
    };
  }

  handleChange = e => {
    if (e.target.files[0]) {
      const image = e.target.files[0];
      this.setState(() => ({ image }));
    }
  };

  handleUpload = () => {
    const { image } = this.state;
    const uploadTask = storage.ref(`images/${image.name}`).put(image);
    uploadTask.on(
      "state_changed",
      snapshot => {
        // progress function ...
        const progress = Math.round(
          (snapshot.bytesTransferred / snapshot.totalBytes) * 100
        );
        this.setState({ progress });
      },
      error => {
        // Error function ...
        console.log(error);
      },
      () => {
        // complete function ...
        storage
          .ref("images")
          .child(image.name)
          .getDownloadURL()
          .then(url => {
            this.setState({ url });
          });
      }
    );
  };
  render() {
    return (
      <div className="center">
          <br/>
          <h2 className="green-text">React Firebase Image Uploader</h2>
          <br/>
          <br/>
        <div className="row">
          <progress value={this.state.progress} max="100" className="progress" />
        </div>
        <br />
        <br />
        <br />
        <div className="file-field input-field">
          <div className="btn">
            <span>File</span>
            <input type="file" onChange={this.handleChange} />
          </div>
          <div className="file-path-wrapper">
            <input className="file-path validate" type="text" />
          </div>
        </div>
        <button
          onClick={this.handleUpload}
          className="waves-effect waves-light btn"
        >
          Upload
        </button>
        <br />
        <br />
        <img
          src={this.state.url || "https://via.placeholder.com/400x300"}
          alt="Uploaded Images"
          height="300"
          width="400"
        />
      </div>
    );
  }
}

export default ImageUpload;
Enter fullscreen mode Exit fullscreen mode

As you can see, I have added some styling using Material css cdn. You can do the same.

There you have it. Simple and clean

Get the code from Github.

Happy hacking!!

Top comments (0)