Building a Firebase-Powered React Application: A Comprehensive Guide for Developers

gladiatorsbattle

Gladiators Battle

Posted on November 18, 2024

Building a Firebase-Powered React Application: A Comprehensive Guide for Developers

Firebase and React are a dynamic duo in the modern web development world. Firebase simplifies backend complexities, while React offers unmatched front-end efficiency. This guide explores how to integrate Firebase into a React application step-by-step, providing detailed insights for developers.

Introduction

In this tutorial, we’ll create a real-time task management application using Firebase and React. Key features include:

Authentication: Firebase Authentication for user sign-in/sign-up.
Database: Firestore for storing tasks.
Hosting: Deploying the app on Firebase Hosting.

Prerequisites

To follow along, ensure you have:

Basic knowledge of React and Firebase.

Node.js installed.

A Firebase account (free tier works fine).

Setting Up the Environment

  1. Initialize React App

Begin by creating a React app:

npx create-react-app task-manager  
cd task-manager  
npm start 
Enter fullscreen mode Exit fullscreen mode
  1. Add Firebase to Your Project

Install Firebase SDK:

npm install firebase

Create a Firebase project:

Go to Firebase Console.

Click "Add Project" and follow the steps.

Once created, navigate to Project Settings > General > Firebase SDK Snippet, and copy the configuration.

Integrating Firebase into React

  1. Set Up Firebase Configuration

Create a firebase.js file in src/:

import { initializeApp } from "firebase/app";  
import { getAuth } from "firebase/auth";  
import { getFirestore } from "firebase/firestore";  

const firebaseConfig = {  
  apiKey: "YOUR_API_KEY",  
  authDomain: "YOUR_PROJECT_ID.firebaseapp.com",  
  projectId: "YOUR_PROJECT_ID",  
  storageBucket: "YOUR_PROJECT_ID.appspot.com",  
  messagingSenderId: "YOUR_SENDER_ID",  
  appId: "YOUR_APP_ID"  
};  

const app = initializeApp(firebaseConfig);  
export const auth = getAuth(app);  
export const db = getFirestore(app); 
Enter fullscreen mode Exit fullscreen mode

Building Features

  1. Authentication

Firebase Authentication simplifies user login. We'll create a sign-up and login form.

Sign-Up Component

import React, { useState } from "react";  
import { auth } from "../firebase";  
import { createUserWithEmailAndPassword } from "firebase/auth";  

function SignUp() {  
  const [email, setEmail] = useState("");  
  const [password, setPassword] = useState("");  

  const handleSignUp = async () => {  
    try {  
      await createUserWithEmailAndPassword(auth, email, password);  
      alert("User Registered Successfully");  
    } catch (error) {  
      alert(error.message);  
    }  
  };  

  return (  
    <div>  
      <h2>Sign Up</h2>  
      <input  
        type="email"  
        placeholder="Email"  
        value={email}  
        onChange={(e) => setEmail(e.target.value)}  
      />  
      <input  
        type="password"  
        placeholder="Password"  
        value={password}  
        onChange={(e) => setPassword(e.target.value)}  
      />  
      <button onClick={handleSignUp}>Sign Up</button>  
    </div>  
  );  
}  

export default SignUp;  
Enter fullscreen mode Exit fullscreen mode

Login Component

Follow a similar approach, but use signInWithEmailAndPassword for login functionality.

  1. Firestore Database Let’s create a real-time task list where users can add, edit, and delete tasks.

Adding Tasks

import { db } from "../firebase";  
import { collection, addDoc } from "firebase/firestore";  

function AddTask() {  
  const [task, setTask] = useState("");  

  const handleAddTask = async () => {  
    try {  
      await addDoc(collection(db, "tasks"), {  
        name: task,  
        completed: false,  
      });  
      setTask("");  
    } catch (error) {  
      console.error("Error adding document: ", error);  
    }  
  };  

  return (  
    <div>  
      <input  
        type="text"  
        placeholder="Add Task"  
        value={task}  
        onChange={(e) => setTask(e.target.value)}  
      />  
      <button onClick={handleAddTask}>Add Task</button>  
    </div>  
  );  
}  

export default AddTask;
Enter fullscreen mode Exit fullscreen mode

Displaying Tasks

import { useEffect, useState } from "react";  
import { db } from "../firebase";  
import { collection, onSnapshot } from "firebase/firestore";  

function TaskList() {  
  const [tasks, setTasks] = useState([]);  

  useEffect(() => {  
    const unsubscribe = onSnapshot(collection(db, "tasks"), (snapshot) => {  
      setTasks(snapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() })));  
    });  
    return () => unsubscribe();  
  }, []);  

  return (  
    <ul>  
      {tasks.map((task) => (  
        <li key={task.id}>{task.name}</li>  
      ))}  
    </ul>  
  );  
}  

export default TaskList;
Enter fullscreen mode Exit fullscreen mode

Deployment with Firebase Hosting

  1. Install Firebase Tools

npm install -g firebase-tools

  1. Initialize Hosting

Run the following commands:

firebase login  
firebase init hosting 
Enter fullscreen mode Exit fullscreen mode

Select your project.

Set the build directory to build.

  1. Build and Deploy
npm run build
firebase deploy
Enter fullscreen mode Exit fullscreen mode

Your app will now be live on Firebase Hosting!

Conclusion

Congratulations! You’ve built a task management app using Firebase and React, complete with authentication, database integration, and hosting. Firebase’s seamless integration with React enables powerful, scalable applications.

Join the Indie Revolution
Are you ready to showcase your game? Here’s how you can get started:

🌐 Visit the Indie Games Showcase: https://gladiatorsbattle.com/indie-games
📢 Follow us on Twitter: https://x.com/GladiatorsBT

Stay connected with us:
🌟 https://discord.gg/YBNF7KjGwx | https://gladiatorsbattle.com/

Let’s make the indie gaming world a better place—one game at a time. 🎮✨

💖 💪 🙅 🚩
gladiatorsbattle
Gladiators Battle

Posted on November 18, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related