Login, Registration and Logout into ReactJS – CODEDEC (2024)

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 ofThis article.
  • Navigate to another page
  • Implement Logout functionality.

Create a user

  • PleaseRead this articleto 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.Login, Registration and Logout into ReactJS – CODEDEC (1)

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.

Login, Registration and Logout into ReactJS – CODEDEC (2)

Navigate to another page

  • After creating this Registration functionality, create another component.

Login, Registration and Logout into ReactJS – CODEDEC (3)

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.

Login, Registration and Logout into ReactJS – CODEDEC (4)

  • 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

Login, Registration and Logout into ReactJS – CODEDEC (5)

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

Login, Registration and Logout into ReactJS – CODEDEC (6)

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;

Login, Registration and Logout into ReactJS – CODEDEC (7)

  • Click on Logout

Login, Registration and Logout into ReactJS – CODEDEC (8)

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.

Login, Registration and Logout into ReactJS – CODEDEC (2024)
Top Articles
Where to post jobs for free: Craigslist and beyond
‘House of the Dragon’ Season 2, episode 2 recap: Beware the satisfaction of petty vengeance | CNN
Swissport Timecard
排期 一亩三分地
Kpschedule Lawson
211475039
Smoke Terminal Waterbury Photos
Sarah Bustani Boobs
Best Transmission Service Margate
Frank 26 Forum
Minneapolis Rubratings
Black Adam Showtimes Near Kerasotes Showplace 14
Bullocks Grocery Weekly Ad
Honda Accord 2012 gebraucht - AutoUncle
Blind Guardian - The God Machine Review • metal.de
Craigslist Shelves
Traveltalkonline
Juliewiththecake Wiki / Biography - Age, Boyfriend, Height, Net Worth - WikiBravo
The Four Fours Puzzle: To Infinity and Beyond!
Amsterdam, Netherlands to PST - Savvy Time
Mynorthwoodtech
David Knowles, journalist who helped make the Telegraph podcast Ukraine: The Latest a runaway success
Jennifer Beals Bikini
Numerous people shot in Kentucky near Interstate 75, officials say | CNN
Seanna: meaning, origin, and significance explained
Baddiehub Cover
Louisiana Funeral Services and Crematory | Broussard, Louisiana
Panty Note Manga Online
Magicseaweed Bob Hall
Maven 5X30 Scope
Sterling Primary Care Franklin
Helloid Worthington Login
More on this Day - March, 7
Big Boobs Indian Photos
Did Hannah Jewell Leave Wnem Tv5
Green Warriors of Norway: “Salvage the 67 tonnes mercury bomb now” | Norges Miljøvernforbund
Dicks Sporting Good Lincoln Ne
8004966305
Glassbox Eyecare
Black Adam Showtimes Near Cinemark Texarkana 14
Raz-Plus Literacy Essentials for PreK-6
Mvsu Canvas
Sam's Club Gas Price Hilliard
Honda Fury Forums
My Vcccd
Webworx Call Management
Broadcastify Thurston County
Deml Ford Used Cars
Stafford Rotoworld
Ohio (OH) Lottery Results & Winning Numbers
SF bay area cars & trucks "chevrolet 50" - craigslist
Funny Roblox Id Codes 2023
Latest Posts
Article information

Author: Stevie Stamm

Last Updated:

Views: 6425

Rating: 5 / 5 (80 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Stevie Stamm

Birthday: 1996-06-22

Address: Apt. 419 4200 Sipes Estate, East Delmerview, WY 05617

Phone: +342332224300

Job: Future Advertising Analyst

Hobby: Leather crafting, Puzzles, Leather crafting, scrapbook, Urban exploration, Cabaret, Skateboarding

Introduction: My name is Stevie Stamm, I am a colorful, sparkling, splendid, vast, open, hilarious, tender person who loves writing and wants to share my knowledge and understanding with you.