Login authentication in react js

In the last video of the series where we will take a look at how we can make routes protected Protected routes are those routes that only grant access to authenticated users. This means that users must first meet certain conditions before accessing that specific route. Our application can require only logged-in users to be able to visit the dashboard page.

so let’s get started

Step 01.

First of all, we need to install React Router Dom with the help of this we will be able to make routing in our application. Open the terminal Copy and run the command below in your app directory

npm install react-router-dom

Step 02:

So now let’s go to the App.js Component and import the following from react-router-dom

import { BrowserRouter, Route, Routes } from "react-router-dom";

after importing now grab everything that you have an inside return() in your app.js component in <BrowserRouter> and then <Routes> and inside Routes define Route in our case we have Login which will appear on the front and the Dashboard screen will appear on /screen

Route accepts few props

  1. the path can be anything depending on your needs
  2. the element here you will have to pass the component that you want to display when users will hit the path

e.g

<BrowserRouter>
<Routes>
<Route path="/" element={<Login />} />
<Route
path="/dashboard"
element={
<Protected>
  <Dashboard />
</Protected>
}
/>
</Routes>
</BrowserRouter>

Step 03:

In the previous tutorial, we had a function called handleSubmit which we were calling on form Submit so head over to that function and below the Axios success response type the below code because we want the users to our dashboard after a successful login

Login Authentication in React Js

import { useNavigate } from "react-router-dom";
const navigate = useNavigate();
navigate("/dashboard");

Step 04:

It’s time to make the routes protected so only logged in users can see our Dashboard page/component

Let’s create a generic component called Protected inside Src folder inside this component we will get item the token from our localstorage and will see if token doesn’t exist it means user is not logged in redirect him/her to the login page to login first.

import React from "react";
import { Navigate } from "react-router-dom";

const Protected = (children) => {
	const token = localStorage.getItem("token");

	if (!token) {
		return <Navigate to="/" replace />;
	}
	return children;
};

export default Protected;

Now go back to the App.js component and in the Route pass this protected component to an element props e.g

That’s it. If you guys have any query please feel free to write comment down below

Enjoy 🙂