Create Registration and Login in ReactJS using google firebase

To maintain user authentication and authorization sometime we have to add a Login and Registration form in ReactJS.

In this article, we will be learning how to create a registration and login into ReactJS. Below are the steps that we will follow,

  • Setup the project environment
  • Initialize React Router
  • Create Registration and Login Form with React Form Hook
  • Get form data
  • Initialize google firebase
  • Create User
  • Login User

Setup the project environment

  • Go to the project directory and create a components folder.
  • Create a functional component named, Register into that.

import React from 'react';

const Registration = () => {
    return (
        <div>

        </div>
    );
};

export default Registration;
  • Create another functional component for Login as well

import React from 'react';

const Login = () => {
    return (
        <div>

        </div>
    );
};

export default Login;

Initialize React Router

  • Install react-router into the project folder by running the below command
npm install react-router-dom@6
  • Import the Registration and Login component into App.js file and put them inside <Routes> and <Route>
return (
    <div >
      {/* declare route container */}
      <Routes>
        <Route path="/" element={<Registration />} />
        <Route path="/registration" element={<Registration />} />
        <Route path="/login" element={<Login />} />
      </Routes>
    </div>
  );
import React, { useState, useEffect } from "react";
import { Route, Routes } from "react-router-dom";
import Login from "./components/Login";
import Registration from "./components/Registration";



const App = () => {

  return (
    <div >
      {/* declare route container */}
      <Routes>
        <Route path="/" element={<Registration />} />
        <Route path="/registration" element={<Registration />} />
        <Route path="/login" element={<Login />} />
      </Routes>
    </div>
  );
}

export default App

Note: To know more details about Routing around the path, Please read this article.

Create registration and login form using react-hook-form

  • Install react-hook-form into the project folder by running this command,
npm install react-hook-form
  • Create a registration form in the Registration component
import React from 'react';
import { Link } from 'react-router-dom'
const Registration = () => {
    return (
        <div className=" flex justify-center lg:h-screen items-center">
            <div className="card w-full md:w-96 items-center shadow-2xl bg-base-100">
                <form className="card-body w-full lg:w-96">
                    <div className="form-control">
                        <label className="label">
                            <span className="label-text">Name</span>
                        </label>
                        <input
                            type="text" placeholder="name" className="input input-bordered" />

                    </div>

                    <div className="form-control">
                        <label className="label">
                            <span className="label-text">Email</span>
                        </label>
                        <input

                            type="email" placeholder="email" className="input input-bordered" />

                    </div>
                    <div className="form-control">
                        <label className="label">
                            <span className="label-text">Password</span>
                        </label>
                        <input

                            type="password" placeholder="password" className="input input-bordered" />



                    </div>
                    <div className="form-control mt-6">
                        <button type="submit" className="btn">Register</button>
                    </div>

                </form>


                <label className="mt-2">
                    Already have an account? <Link to="/login" className="btn btn-link text-white underline px-0">Login</Link>
                </label>
            </div>
        </div>
    );
};

export default Registration;

Here, we have created a Registration form in JSX. We have used Tailwind CSS to style this component. To know about setup the environment with Tailwind CSS, Read this article.

  • Use react-form-hooks functionalities to register data and show errors if the input field remains empty white registering.
import { useForm } from "react-hook-form";
const { register, handleSubmit, watch, formState: { errors }, reset } = useForm();
    const onSubmit = data => {

        console.log(data)
    };
  • Initialize register to each input form
{...register("name", { required: true })}

Note: To know more details about getting form data using react-hook-form, Read this article

import React from 'react';
import { Link } from 'react-router-dom';
import { useForm } from "react-hook-form";
const Registration = () => {

    const { register, handleSubmit, watch, formState: { errors }, reset } = useForm();

    const onSubmit = data => {
        console.log(data)
    };
    return (
        <div className=" flex justify-center lg:h-screen items-center">
            <div className="card w-full md:w-96 items-center shadow-2xl bg-base-100">
                <form onSubmit={handleSubmit(onSubmit)} className="card-body w-full lg:w-96">
                    <div className="form-control">
                        <label className="label">
                            <span className="label-text">Name</span>
                        </label>
                        <input
                            {...register("name", { required: true })}
                            type="text" placeholder="name" className="input input-bordered" />
                        <span className="label-text text-error">{errors.email?.type === 'required' && "Name is required"}</span>
                    </div>

                    <div className="form-control">
                        <label className="label">
                            <span className="label-text">Email</span>
                        </label>
                        <input
                            {...register("email", { required: true })}
                            type="email" placeholder="email" className="input input-bordered" />
                        <span className="label-text text-error">{errors.email?.type === 'required' && "Email is required"}</span>
                    </div>
                    <div className="form-control">
                        <label className="label">
                            <span className="label-text">Password</span>
                        </label>
                        <input
                            {...register("password", { required: true })}
                            type="password" placeholder="password" className="input input-bordered" />
                        <span className="label-text text-error">{errors.password && "Password is required"}</span>


                    </div>
                    <div className="form-control mt-6">
                        <button type="submit" className="btn">Register</button>
                    </div>

                </form>


                <label className="mt-2">
                    Already have an account? <Link to="/login" className="btn btn-link text-white underline px-0">Login</Link>
                </label>
            </div>
        </div>
    );
};

export default Registration;

Note: Here, we are using Link from react-router-dom. Which will navigate us to the path that we have selected.

  • Create a login form as well in the Login component just like the Registration form.
import { useForm } from "react-hook-form";
const { register, handleSubmit, watch, formState: { errors }, reset } = useForm();
    const onSubmit = data => {

        console.log(data)
    };

Here, this data parameter will give us all the input field values as an object. With errors, we will get all the errors, and with reset we can remove the input field values after submission.

import React from 'react';
import { useForm } from "react-hook-form";
import { Link } from 'react-router-dom'
const Login = () => {

    const { register, handleSubmit, watch, formState: { errors }, reset } = useForm();

    const onSubmit = data => {
        console.log(data)
    };
    return (
        <div className=" flex justify-center lg:min-h-screen items-center">
            <div className="card w-full md:w-96 items-center shadow-2xl bg-base-100">
                <form onSubmit={handleSubmit(onSubmit)} className="card-body w-full lg:w-96">
                    <div className="form-control">
                        <label className="label">
                            <span className="label-text">Email</span>
                        </label>
                        <input
                            type="email" placeholder="email" className="input input-bordered"
                            {...register("email", { required: true })}

                        />
                        <span className="label-text text-error">{errors.email?.type === 'required' && "Email is required"}</span>
                    </div>
                    <div className="form-control">
                        <label className="label">
                            <span className="label-text">Password</span>
                        </label>
                        <input

                            type="password" placeholder="password" className="input input-bordered"
                            {...register("password", { required: true })} />
                        <span className="label-text text-error">{errors.password?.type === 'required' && "Password is required"}</span>


                    </div>
                    <div className="form-control mt-6">
                        <button type="submit" className="btn ">Login</button>
                    </div>

                </form>

                <label className="mt-2">
                    Don't have an account?<Link to="/registration" className="btn btn-link text-white underline px-0">Register</Link>
                </label>
            </div>
        </div>
    );
};

export default Login;

Get form data

  • Console log the data parameter from useForm(). It will give an object. Inside that object, all the input values will be there.
const onSubmit = data => {
        console.log(data)
    };

Initialize google firebase

  • Install firebase in the project directory by running,
    npm install firebase
  • Create a file named, firebase.init.js inside the src folder in the project directory

  • Copy the firebase SDK and paste those in here.
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAuth } from 'firebase/auth';
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
const firebaseConfig = {
    apiKey: WRITE-YOUR-API-KEY-HERE
    authDomain: WRITE-YOUR-AUTHDOMAIN
    projectId: WRITE-YOUR-PROJECT-ID
    storageBucket: WRITE-YOUR-STORAGE-BUCKET
    messagingSenderId: WRITE-YOUR-SENDER-ID
    appId: WRITE-YOUR-APP-ID
};

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

export default auth;

Note: You should get your own SDK in the firebase console. Keep this in mind, this data should be private and secured.

  • Install react-firebase-hook by the below command,
npm install --save react-firebase-hooks
  • Add sign-in method for Email/password in firebase authentication

Now that the integration of firebase and all the dependencies are set, we can continue to registration and log-in functionalities.

Create user

  • Go to the Registration component and import the below dependencies.
import { useCreateUserWithEmailAndPassword } from 'react-firebase-hooks/auth';
import auth from '../firebase.init';
  • Write the below variable inside the Registration function
const [
        createUserWithEmailAndPassword,
        user,
        loading,
        error,
    ] = useCreateUserWithEmailAndPassword(auth);

Here, if the user registered, we will get data from user, and if any error occurs, we will get those in error.

const [
       createUserWithEmailAndPassword,
       user,
       loading,
       error,
   ] = useCreateUserWithEmailAndPassword(auth);

   const { register, handleSubmit, watch, formState: { errors }, reset } = useForm();

   const onSubmit = data => {
       console.log(data);
       createUserWithEmailAndPassword(data.email, data.password);
   };

Here, we are passing email and password as arguments in the createUserWithEmailAndPassword() function. And we are getting the email and password from the data object.

if (user) {
       console.log(user)
   };
   if (error) {
       console.log(error)
   }

Check whether the user is registering or not and check if there is any error occurring.

import React from 'react';
import { Link } from 'react-router-dom';
import { useForm } from "react-hook-form";

import { useCreateUserWithEmailAndPassword } from 'react-firebase-hooks/auth';
import auth from '../firebase.init';
const Registration = () => {
    const [
        createUserWithEmailAndPassword,
        user,
        loading,
        error,
    ] = useCreateUserWithEmailAndPassword(auth);

    const { register, handleSubmit, watch, formState: { errors }, reset } = useForm();

    const onSubmit = data => {
        console.log(data);
        createUserWithEmailAndPassword(data.email, data.password);
        console.log(user)
        console.log(error)
    };
    if (user) {
        console.log(user)
    };
    if (error) {
        console.log(error)
    }
    return (
        <div className=" flex justify-center lg:h-screen items-center">
            <div className="card w-full md:w-96 items-center shadow-2xl bg-base-100">
                <form onSubmit={handleSubmit(onSubmit)} className="card-body w-full lg:w-96">
                    <div className="form-control">
                        <label className="label">
                            <span className="label-text">Name</span>
                        </label>
                        <input
                            {...register("name", { required: true })}
                            type="text" placeholder="name" className="input input-bordered" />
                        <span className="label-text text-error">{errors.email?.type === 'required' && "Name is required"}</span>
                    </div>

                    <div className="form-control">
                        <label className="label">
                            <span className="label-text">Email</span>
                        </label>
                        <input
                            {...register("email", { required: true })}
                            type="email" placeholder="email" className="input input-bordered" />
                        <span className="label-text text-error">{errors.email?.type === 'required' && "Email is required"}</span>
                    </div>
                    <div className="form-control">
                        <label className="label">
                            <span className="label-text">Password</span>
                        </label>
                        <input
                            {...register("password", { required: true })}
                            type="password" placeholder="password" className="input input-bordered" />
                        <span className="label-text text-error">{errors.password && "Password is required"}</span>


                    </div>
                    <div className="form-control mt-6">
                        <button type="submit" className="btn">Register</button>
                    </div>

                </form>


                <label className="mt-2">
                    Already have an account? <Link to="/login" className="btn btn-link text-white underline px-0">Login</Link>
                </label>
            </div>
        </div>
    );
};

export default Registration;

 

After clicking to Register, in the dev tool, we will get a result if the user successfully registered or not.

The user registered successfully.

Log in user

  • Go to Login component and import the below dependencies there,
import { useSignInWithEmailAndPassword } from 'react-firebase-hooks/auth';
import auth from '../firebase.init';
// importing this from the directory where we have saved it
  • Write the below code inside the Login function
const [
        signInWithEmailAndPassword,
        user,
        loading,
        error,
    ] = useSignInWithEmailAndPassword(auth);

It will work just like registering a user, but this time it will work for logging in a user as we are using, useSignInWithEmailAndPassword()

const { register, handleSubmit, watch, formState: { errors }, reset } = useForm();
    const [
        signInWithEmailAndPassword,
        user,
        loading,
        error,
    ] = useSignInWithEmailAndPassword(auth);
    const onSubmit = data => {
        console.log(data);
        signInWithEmailAndPassword(data.email, data.password)
    };
    if (user) {
        console.log(user)
    };
    if (error) {
        console.log(error)
    };
import React from 'react';
import { useSignInWithEmailAndPassword } from 'react-firebase-hooks/auth';
import { useForm } from "react-hook-form";
import { Link } from 'react-router-dom'
import auth from '../firebase.init';
const Login = () => {

    const { register, handleSubmit, watch, formState: { errors }, reset } = useForm();
    const [
        signInWithEmailAndPassword,
        user,
        loading,
        error,
    ] = useSignInWithEmailAndPassword(auth);
    const onSubmit = data => {
        console.log(data);
        signInWithEmailAndPassword(data.email, data.password)
    };
    if (user) {
        console.log(user)
    };
    if (error) {
        console.log(error)
    };
    return (
        <div className=" flex justify-center lg:min-h-screen items-center">
            <div className="card w-full md:w-96 items-center shadow-2xl bg-base-100">
                <form onSubmit={handleSubmit(onSubmit)} className="card-body w-full lg:w-96">
                    <div className="form-control">
                        <label className="label">
                            <span className="label-text">Email</span>
                        </label>
                        <input
                            type="email" placeholder="email" className="input input-bordered"
                            {...register("email", { required: true })}

                        />
                        <span className="label-text text-error">{errors.email?.type === 'required' && "Email is required"}</span>
                    </div>
                    <div className="form-control">
                        <label className="label">
                            <span className="label-text">Password</span>
                        </label>
                        <input

                            type="password" placeholder="password" className="input input-bordered"
                            {...register("password", { required: true })} />
                        <span className="label-text text-error">{errors.password?.type === 'required' && "Password is required"}</span>


                    </div>
                    <div className="form-control mt-6">
                        <button type="submit" className="btn ">Login</button>
                    </div>

                </form>

                <label className="mt-2">
                    Don't have an account?<Link to="/registration" className="btn btn-link text-white underline px-0">Register</Link>
                </label>
            </div>
        </div>
    );
};

export default Login;

 

It is almost the same as registering a user. We are passing the email and password from the data object. And we will console.log the user; if there is a user logged in else we will get an error which we are checking as well. We will get a result in our dev tool whether it is a successful result or an error.

After clicking login, as you can see, we are getting an object with the data of the logged-in user, hence, the user logged in successfully.

This is how we can create a register and log-in method in ReactJS with the help of google firebase.