Getting Started with React & Firebase

Getting Started with React & Firebase

ยท

5 min read

In this article, we will explore the significance of React and Firebase in web development. We will dive into the process of building a basic user authentication application using these powerful technologies. By combining the frontend capabilities of React with the backend functionality of Firebase, we can create secure and dynamic web applications. Our focus will be on passing user data to Firestore and displaying it on a webpage, showcasing the seamless integration and benefits of React and Firebase.

Why Firebase:

  1. Firebase is a comprehensive platform that offers a range of services essential for modern web development. It eliminates the need for managing separate backend infrastructure, servers, and databases, providing a seamless development experience.

  2. With Firebase, developers can leverage features such as real-time database, user authentication, cloud storage, and serverless functions, enabling rapid development and deployment of web applications.

  3. By integrating Firebase with React, developers can focus on building engaging user interfaces while Firebase handles the backend complexities, making it an ideal choice for efficient and scalable development.

Let's get Started...

Step 1:

Create a new React project:

  • Open your terminal and run the following command to create a new React project using Create React App:
npx create-react-app react-firebase-auth

( This command will create a new directory named react-firebase-auth and set up a basic React project structure inside it )

Install Required Dependencies:

  • Navigate into the project directory by running the following command:
cd react-firebase-auth
  • Now, install the required dependencies by running the following command:

      npm install firebase react-router-dom
    

    This will install the Firebase SDK and React Router DOM, which we'll use for routing in our application.

Step 2:

Set up Firebase project:

  • Go to the Firebase Console console.firebase.google.com and create a new project.

  • Once your project is created, click on "Authentication" in the left menu and enable the "Email/Password" sign-in method.

  • Next, click on "Firestore" in the left menu and create a new Firestore database. Start in "Production" mode and choose a region for your database.

Step 3:

Configure the Firebase inside the React App

  • Inside the project directory, create a new file called firebase.js in the src folder. Open the file and add the following code:

      import firebase from 'firebase/compat/app';
      import 'firebase/compat/auth';
      import 'firebase/compat/firestore';
    
      const firebaseConfig = {
        apiKey: 'YOUR_API_KEY',
        authDomain: 'YOUR_AUTH_DOMAIN',
        projectId: 'YOUR_PROJECT_ID',
        storageBucket: 'YOUR_STORAGE_BUCKET',
        messagingSenderId: 'YOUR_MESSAGING_SENDER_ID',
        appId: 'YOUR_APP_ID',
      };
    
      firebase.initializeApp(firebaseConfig);
    
      export const auth = firebase.auth();
      export const firestore = firebase.firestore();
    

    NOTE: Replace the credentials/placeholders inside the "firebaseConfig" object with your own. It can be found inside the Project Settings.

Step 4:

Creating the components

SignUp.jsx (For registering the user) :

import React, { useState } from 'react';

const SignUp = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleSignUp = () => {
    // Handle sign up logic here
    console.log('Signing up...');
  };

  return (
    <div>
      <h2>Sign Up</h2>
      <form>
        <label htmlFor="email">Email:</label>
        <input
          type="email"
          id="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
        />

        <label htmlFor="password">Password:</label>
        <input
          type="password"
          id="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />

        <button type="button" onClick={handleSignUp}>
          Sign Up
        </button>
      </form>
    </div>
  );
};

export default SignUp;

Login.jsx (For Logging in the user with correct credentials) :

import React, { useState } from 'react';

const Login = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleLogin = () => {
    // Handle login logic here
    console.log('Logging in...');
  };

  return (
    <div>
      <h2>Login</h2>
      <form>
        <label htmlFor="email">Email:</label>
        <input
          type="email"
          id="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
        />

        <label htmlFor="password">Password:</label>
        <input
          type="password"
          id="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />

        <button type="button" onClick={handleLogin}>
          Login
        </button>
      </form>
    </div>
  );
};

export default Login;

Profile.jsx (To display the User's information) :

import React from 'react';

const Profile = ({ user }) => {
  return (
    <div>
      <h2>Profile</h2>
      <p>Welcome, {user.name}!</p>
      <p>Email: {user.email}</p>
      {/* Render other profile information */}
    </div>
  );
};

export default Profile;

( You can add more fields and functionalities as per your requirements )

Step 5:

Setting up the routes

  • Inside the prebuilt App.js in the src folder, replace the already mentioned code with the following code:

      import React from 'react';
      import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
      import SignUp from './components/Auth/SignUp';
      import Login from './components/Auth/Login';
      import Profile from './components/Auth/Profile';
      import Home from './components/Home';
    
      function App() {
        return (
          <Router>
            <Routes>
              <Route path="/" element={<SignUp />} />
              <Route path="/login" element={<Login />} />
              <Route path="/profile" element={<Profile />} />
              <Route path="/home" element={<Home />} />
            </Routes>
          </Router>
        );
      }
    
      export default App;
    

Step 6:

Importing the packages

  • Import the following packages at the top of the Files:

  •       import React, { useEffect, useState } from 'react';
          import { Link, Navigate } from 'react-router-dom';
          import { auth, firestore } from './firebase';
    

Your Directory structure should roughly Look Like this

src/
  |- components/
  |    |- Auth/
  |    |    |- SignUp.jsx
  |    |    |- Login.jsx
  |    |    |- Profile.jsx
  |    |
  |    |- Home.jsx
  |
  |- firebase/
  |    |- firebase.jsx
  |
  |- App.jsx
  |- index.jsx

Take a Look at the Results:

SignUp page:

Login Page:

Profile Page:

NOTE: I have used a lot less CSS. You can add custom CSS to make it look Fab!๐Ÿ’ฏ

Thus, we have finally made a Basic User Authentication application using React and Firebase.

Ping me on LinkedIn in case you are stuck in any issues ๐Ÿ™‚

My LinkedIn: https://www.linkedin.com/in/sujal-soni

Get full code here: https://github.com/Sujal-2820/React-Authentication-Application.git

ย