Skip to content

Instantly share code, notes, and snippets.

@agmm
Created January 30, 2021 15:23
Show Gist options
  • Save agmm/5ceeff55a5e658365b5ce258c235cbdd to your computer and use it in GitHub Desktop.
Save agmm/5ceeff55a5e658365b5ce258c235cbdd to your computer and use it in GitHub Desktop.
Upload file to a firebase storage bucket — React
import React, { useState } from "react";
import firebase from "firebase";
import "firebase/storage";
const firebaseConfig = {};
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
export const storage = firebase.storage();
function UploadForm() {
const [file, setFile] = useState(null);
const [url, setURL] = useState("");
function handleChange(e) {
setFile(e.target.files[0]);
}
function handleUpload(e) {
e.preventDefault();
const uploadTask = storage.ref(`/images/${file.name}`).put(file);
uploadTask.on("state_changed", console.log, console.error, () => {
storage
.ref("images")
.child(file.name)
.getDownloadURL()
.then((url) => {
setFile(null);
setURL(url);
});
});
}
return (
<div>
<form onSubmit={handleUpload}>
<input type='file' onChange={handleChange} />
<button disabled={!file}>Upload to firebase</button>
</form>
<img src={url} alt='' />
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment