【Firebase】ボタンを押したとき送信されるようにする

firebase.js

import { initializeApp } from "firebase/app";
import { getStorage } from "firebase/storage";

const firebaseConfig = {
  apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
  authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
  storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.REACT_APP_FIREBASE_APP_ID,
  measurementId: process.env.REACT_APP_FIREBASE_MEASUREMENT_ID
};

const app = initializeApp(firebaseConfig);
export const storage = getStorage(app);

App.jsx

import React from 'react';
import Upload from './Upload';

const App = () => {
  return (
    <React.Fragment>
      <Upload />
    </React.Fragment>
  );
}

export default App;

Upload.jsx

import React, { useState } from 'react';
import { ref, uploadBytes } from 'firebase/storage';
import { storage } from '../scripts/firebase';

const Upload = () => {
  const [files, setFiles] = useState([]);

  const handleInputChange = (event) => {
    const fileList = Array.from(event.target.files);
    setFiles(fileList);
  }

  const handleSubmit = (event) => {
    event.preventDefault();
    files.forEach((file) => {
      const storageRef = ref(storage, `images/${file.name}`);
      uploadBytes(storageRef, file).then(() => {
        console.log('Uploaded!');
      });
    });
  }

  return (
    <React.Fragment>
      <form>
        <input
          type='file'
          accept='image/*'
          multiple
          onChange={handleInputChange}
        />
        <button type='submit' onClick={handleSubmit}>送信</button>
      </form>
    </React.Fragment>
  );
}

export default Upload;
タイトルとURLをコピーしました