How to upload images in firebase storage with React.js.
Tags: react, firebase, database, writing
Published: 2021-02-24 04:17:08

Hi everyone, I hope you all are safe and doing fine!
Here, we will be uploading an image in firebase storage.
If you're already familiar with JavaScript, React and Firebase, then you'll be able to get moving with this quickly!

##Explanation
First create the project using command
`npx create-react-app firebase-tutorial`

then install the packages that needed for the navigations

`yarn add firebase`

After installing the project add new folder named as firebase and create new file in folder. The file structure should be as follows
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/lgus5nwz1a98p0hrnqnj.png)

Now its time to create new project on firebase.
[Click here](https://console.firebase.google.com/u/0/).
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wc0xd1hzvuckmet7c5ef.png)
Click on Add Project

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sp3bfuuhrugko6gfsw8a.png)

Enter your project name.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c5bt4guzlek09356cyhs.png)

Click on create project.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w7wgqf3vobghw3gt6jhg.png)
Now add Web app on clicking </> this.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/stvum17tjz4r5kq98c37.png)
Register your app name.Ex- firebase-image. Click on Register app.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fbl6x8y4dog4lhhji1ke.png)

copy this snippet and paste this snippet in firebase.js file.
firebase.js should look like this.
```js
import firebase from 'firebase'

var firebaseConfig = {
  apiKey: "******rBJcUIyThYVrIqg",
  authDomain: "********.firebaseapp.com",
  projectId: "************",
  storageBucket: "**********.appspot.com",
  messagingSenderId: "***************",
  appId: "*****************df5dfbbee0"
};
  firebase.initializeApp(firebaseConfig);
  export default firebase;
```
Click on storage icon on left sidebar. Now click on Rules. your rules should look like this. 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wk7jv82a8pkfpi8qw6jg.png)
Change the code and publish.Now your rules changes and should look like this.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wvzwnovt90t5t74hvkqw.png)

Now its time to code. Open App.js and follow the below code.
```js
import React, { Component } from 'react'
import './App.css';
import firebase from "./firebase/firebase"

export default class App extends Component {
  constructor(){
    super();
    this.state = {
      image: null,
      progress:0,
      downloadURL: null
    }
  }


  handleChange = (e) =>{
    if(e.target.files[0]){
      this.setState({
      image: e.target.files[0]
    })
  }
    // console.log(e.target.files[0])
}

handleUpload = () =>{
  // console.log(this.state.image);
  let file = this.state.image;
  var storage = firebase.storage();
  var storageRef = storage.ref();
  var uploadTask = storageRef.child('folder/' + file.name).put(file);

  uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
    (snapshot) =>{
      var progress = Math.round((snapshot.bytesTransferred/snapshot.totalBytes))*100
      this.setState({progress})
    },(error) =>{
      throw error
    },() =>{
      // uploadTask.snapshot.ref.getDownloadURL().then((downloadURL) =>{

      uploadTask.snapshot.ref.getDownloadURL().then((url) =>{
        this.setState({
          downloadURL: url
        })
      })
    document.getElementById("file").value = null

   }
 ) 
}


  render() {
    return (
      <div className="App">
        <h4>upload image</h4>
        <label>
          Choose file
        <input type="file" id="file" onChange={this.handleChange} />        
        </label>

        {this.state.progress}
        <button className="button" onClick={this.handleUpload}>Upload</button>
        <img
          className="ref"
          src={this.state.downloadURL || "https://via.placeholder.com/400x300"}
          alt="Uploaded Images"
          height="300"
          width="400"
        />
      </div>
    )
  }
}
```
CSS
```css
.App {
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}



label{
  align-items: center;
  padding: 12px;
  background: red;
  display: table;
  color: #fff;
  /* margin-left: 700px; */
  /* padding-inline: 40px; */
   }

   .button {
    background-color: #4CAF50; /* Green */
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    margin: 4px 2px;
    cursor: pointer;
  }
.ref{
  margin-top: auto;
}

input[type="file"] {
  display: none;
}

```
Now run the file using command
``` npm start ```

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a9zmf8na26dmho1vjygh.png)

AND DONE
I hope you liked the article!
Thank You!