How to connect firebase database (firestore) to react

#tutorial

Steps#

  1. Go to firebase console and create a new project (or open an existing project). You don't need to enable Google Analytics for your Firebase project.

  2. Click on the web icon on Project Overview

    alt

  3. Click on register app and copy the code for your configuration. Your configuration will look like this:

    alt

  4. In your react project, create a file named firebase.js in the same directory as App.js and paste the code there.

  5. Import getFirestore in firebase.js using import { getFirestore } from "firebase/firestore";, add const firestore = getFirestore(app); after initializeApp and finally export this firestore. Your code should now look like this:

import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore'; // add this

// Your web app's Firebase configuration
const firebaseConfig = {
  apiKey: 'AIzaSyAlJdfLqGwKF8lFrxyBsjlK7oKwcwOrqDs',
  authDomain: 'temp-379c3.firebaseapp.com',
  projectId: 'temp-379c3',
  storageBucket: 'temp-379c3.appspot.com',
  messagingSenderId: '677359605826',
  appId: '1:677359605826:web:4b349ec0fd147f1d74b5db'
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

const firestore = getFirestore(app); // add this

export { firestore }; // add this
  1. Add firebase package in your dependency using npm i firebase or yarn add firebase.

  2. To add data in firestore database, you need to use addDoc method. Here's an example code which stores input data in users collections on form submission:

import React, { useState } from 'react';
import { addDoc, collection } from '@firebase/firestore';
import { firestore } from '../firebase'; // your firebase.js directory

export default function Form() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');

  // reference to users collection in your firestore databse (will be created if not available)
  const ref = collection(firestore, 'users');

  const handleSubmit = (e) => {
    e.preventDefault();

    let data = {
      name: name,
      email: email
    };

    try {
      // add document (data) to referenced (users) collection
      addDoc(ref, data);
    } catch (err) {
      console.log(err);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        name="name"
        value={name}
        onChange={(e) => setName(e.target.value)}
        placeholder="Name"
        required
      />
      <input
        type="email"
        name="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder="Email address"
        required
      />
      <button type="submit">Submit</button>
    </form>
  );
}

Note that firestore is a NoSQL database. Data are stored as documents, which are organized into collections. Document is basically a JSON object but supports extra data types.

  1. We're done! You can check and verify the data in your Firebase console in Firestore page.