Login, Registration and Logout into ReactJS

In every user authentication implementation, three things are necessary to implement. Registration, Login, and Logout. In this reactJS tutorial, let’s create ReactApplication to perform Login, Registration, and logout operations.

With Registration, the user can create an account and get to the desired page, with Login, the user can log in with email and password and get to the desired page and if the user wants to log out from the page, the user will go for the Logout.

First, we have to implement Register and login functionality for it then after registering user will be able to see a Logout button. After clicking that, the user will be logged out.

Note: To know how to implement Register and Login functionality to a React project, Please read this article carefully.

Below are the steps that we will be following,

  • Create a user with the help of This article.
  • Navigate to another page
  • Implement Logout functionality.

Create a user

  • Please Read this article to know how to create a user. Below is the code in the Registration component.
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;

Here, we have created a component named Registration inside the folder named, components which is in the src folder.

After importing this Registration component in App.js,

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

Here we are using react-router to navigate the user. To know more about navigation in React, Please read this article.

Navigate to another page

  •  After creating this Registration functionality, create another component.

import React from 'react';

const Home = () => {
    return (
        <div>
            
        </div>
    );
};

export default Home;
  • Create a navigation bar in this component.
import React from 'react';

const Home = () => {
    return (
        <div>
            <div className="navbar bg-base-100">
                <div className="flex-1">
                    <a className="btn btn-ghost normal-case text-xl">Homepage</a>
                </div>
                <div className="flex-none">
                    <ul className="menu menu-horizontal p-0">
                        <li><a>About</a></li>
                        <li><a>Blog</a></li>
                        <li><a>Contact</a></li>
                        <li><a>Register</a></li>
                    </ul>
                </div>
            </div>
        </div>
    );
};

export default Home;
  • Import this component to App.js and set a route for it.
import React, { useState, useEffect } from "react";
import { Route, Routes } from "react-router-dom";
import Home from "./components/Home";
import Registration from "./components/Registration";



const App = () => {

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

export default App

Here, we have set the default path ‘/’ to this Home component so this will be the landing page. And in the navbar, we can see the Register button there. By clicking it, the user will be taken to the Register page that we have created.

  • Add the below code to the Register button in the Home component.
<li><Link to="/registration" className='btn'>Register</Link></li>

What we are doing is, that if the user clicks on the Register button, it will take the user to the Register page.

Make sure in the App component the route is set to '/registration' as well.

<Route path="/registration" element={<Registration />} />
import React from 'react';
import { Link } from 'react-router-dom';

const Home = () => {
    return (
        <div>
            <div className="navbar bg-base-100">
                <div className="flex-1">
                    <a className="btn btn-ghost normal-case text-xl">Homepage</a>
                </div>
                <div className="flex-none">
                    <ul className="menu menu-horizontal p-0">
                        <li><a>About</a></li>
                        <li><a>Blog</a></li>
                        <li><a>Contact</a></li>
                        <li><Link to="/registration" className='btn'>Register</Link></li>
                    </ul>
                </div>
            </div>
        </div>
    );
};

export default Home;
  • Import useNavigate() hook in the Registration page.
import { Link, useNavigate } from 'react-router-dom';
  • Write the below condition in the Register function.
const navigate = useNavigate();
   useEffect(() => {
       if (user) {
           navigate('/');
       } else {
           alert('Something went wrong')
       }
   }, [user, navigate])

We will get a user after registration. If the user registered successfully, it will take the user directly to the Home component (homepage).

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

import { useCreateUserWithEmailAndPassword } from 'react-firebase-hooks/auth';
import auth from '../firebase.init';
import { useEffect } from 'react';
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)
    };
    const navigate = useNavigate();
    useEffect(() => {
        if (user) {
            navigate('/');
        } else {
            alert('Something went wrong')
        }
    }, [user, navigate])
    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;
  • Go to the Home component and write the below code there.
 import { useAuthState } from 'react-firebase-hooks/auth';
 const [user, loading, error] = useAuthState(auth);

After registering, we will get the user data inside this user variable that we are destructuring from useAuthState() hook.

  • Add the Logout and Register button inside the ternary operator in the Navbar in the Home component.
 <li>{!user ? <Link to="/registration" className='btn'>Register</Link> : <button className='btn'>Logout</button>}</li>

We have added the buttons inside the ternary operator which will check if the user exists or not. If the user doesn’t exist then we will see the Register button else, the Logout button.

import React from 'react';
import { useAuthState } from 'react-firebase-hooks/auth';
import { Link } from 'react-router-dom';
import auth from '../firebase.init';

const Home = () => {
    const [user, loading, error] = useAuthState(auth);
    return (
        <div>
            <div className="navbar bg-base-100">
                <div className="flex-1">
                    <a className="btn btn-ghost normal-case text-xl">Homepage</a>
                </div>
                <div className="flex-none">
                    <ul className="menu menu-horizontal p-0">
                        <li><a>About</a></li>
                        <li><a>Blog</a></li>
                        <li><a>Contact</a></li>
                        <li>{!user ? <Link to="/registration" className='btn'>Register</Link> : <button className='btn'>Logout</button>}</li>
                    </ul>
                </div>
            </div>
        </div>
    );
};

export default Home;

As of now, we will be seeing the Register button as we haven’t created any account yet.

  • Go to the Register page and create an account

After clicking Register, it will navigate to Home. And in the navbar, the Register button will be replaced by the Logout button

Implement Logout

  • Write an onClick() event to the Logout button in the navbar and add a function there to implement the logout functionality.
<li>{!user ? <Link to="/registration" className='btn'>Register</Link> : <button className='btn' onClick={handleLogout}>Logout</button>}</li>
const handleLogout = ()=>{

}
  • Import signOut.
import { signOut } from 'firebase/auth';
  • Add this signOut to the handleLogout() function
const handleLogout = () => {
        signOut(auth)
    }
  • Write the below codes outside of this handleLogout() function
  const navigate = useNavigate()
    useEffect(() => {
        if (!user) {

            navigate('/registration')
        }
    }, [user, navigate])

Here, we are using navigation again so that, if the user account is not here then it will navigate to '/registration' route.

import React from 'react';
import { useAuthState } from 'react-firebase-hooks/auth';
import { Link, Navigate, useNavigate } from 'react-router-dom';
import auth from '../firebase.init';
import { signOut } from 'firebase/auth';
import { useEffect } from 'react';
const Home = () => {
    const [user, loading, error] = useAuthState(auth);
    const handleLogout = () => {
        signOut(auth)
    }

    const navigate = useNavigate()

    useEffect(() => {
        if (!user) {
            navigate('/registration')
        }
    }, [user, navigate])

    return (
        <div>
            <div className="navbar bg-base-100">
                <div className="flex-1">
                    <a className="btn btn-ghost normal-case text-xl">Homepage</a>
                </div>
                <div className="flex-none">
                    <ul className="menu menu-horizontal p-0">
                        <li><a>About</a></li>
                        <li><a>Blog</a></li>
                        <li><a>Contact</a></li>
                        <li>{!user ? <Link to="/registration" className='btn'>Register</Link> : <button className='btn' onClick={handleLogout}>Logout</button>}</li>
                    </ul>
                </div>
            </div>
        </div>
    );
};

export default Home;

  • Click on Logout

As we can see, it directly will take us to the Registration.

This is how we can implement Logout functionality in a React app. Here we have shown how to do it by Registering a user. The same thing can be done by Login. Same thing we have to do on the Login page as well. We just have to check if the user account can be found or not. if it has been found, then it will navigate us to the homepage just like we did it for registration.