Skip to content
  • Thursday, August 4, 2022
Blokland Prive Vakantiehuizen

Blokland Prive Vakantiehuizen

  • Home
  • Website checker
  • Website login
  • Website file
  • Website maker
  • Website Store
  • Privacy Policy
  • Terms and Conditions
  • Home
  • Website login
  • How to redirect a user after login in React
Website login

How to redirect a user after login in React

July 15, 2022
Sarah N. Randall

Usually, when building web applications, login pages are used to protect private pages. For example, for a blogging platform, the dashboard might only be accessible to authenticated users. If an unauthenticated user tries to access this page, the application redirects him to the login page. Once connected, they have access to it.

USE VIDEO OF THE DAY

In this article, we will see how you can redirect a user from a restricted page to a login page. We will also discuss how you can return the user to the page they were on after logging in.

In React Router v6, you can use two methods to redirect a user: the Navigate component and the useNavigate() to hang up.

Create a responsive app

Create a simple React application using the create-react-app ordered. You will use this application to test how the Navigate component and the useNavigate() crochet work.

npx create-react-app react-redirect

Create a login page

You will need to create a login page to authenticate users. Since this is not an authentication tutorial, use an array of objects as the user database.

Create a new file in the src folder and name it Login.js. Then add the following code, to create the login form.

import { useState } from "react";
import Dashboard from "./Dashboard";
const Login = () => {
const [username, setusername] = useState("");
const [password, setpassword] = useState("");
const [authenticated, setauthenticated] = useState(localStorage.getItem(localStorage.getItem("authenticated")|| false));
const users = [{ username: "Jane", password: "testpassword" }];
const handleSubmit = (e) => {
e.preventDefault()
const account = users.find((user) => user.username === username);
if (account && account.password === password) {
setauthenticated(true)
localStorage.setItem("authenticated", true);
}
};
return (
<div>
<p>Welcome Back</p>
<form onSubmit={handleSubmit}>
<input
type="text"
name="Username"
value={username}
onChange={(e) => setusername(e.target.value)}
/>
<input
type="password"
name="Password"
onChange={(e) => setpassword(e.target.value)}
/>
<input type="submit" value="Submit" />
</form>
</div>
)
};
}
export default Login;

This is a simple login form. When a user submits their username and password, they are checked against the table. If this information is correct, the authenticated state is set to true. Since you will be checking if the user is authenticated in the Dashboard component, you should also store the authentication state somewhere accessible by other components. This article uses local storage. In a real application, using the React context would be a better choice.

Create a dashboard page

Add the following code in a new file called Dashboard.js.

const Dashboard = () => {
return (
<div>
<p>Welcome to your Dashboard</p>
</div>
);
};
export default Dashboard;

The dashboard should only be accessible to authenticated users. Therefore, when users visit the dashboard page, first check if they are authenticated. If not, redirect them to the login page.

To do this, first configure the application routes using the React router.

npm install react-router-dom

In index.js, configure your application’s routing.

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Login from "./Login";
import Dashboard from "./Dashboard";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<BrowserRouter>
<Routes>
<Route index element={<App />} />
<Route path="login" element={<Login />} />
<Route path="dashboard" element={<Dashboard />} />
</Routes>
</BrowserRouter>
</React.StrictMode>
);

Protect Dashboard Page

Now that your application routes are configured, the next step is to make the dashboard route private. When loading the Dashboard component, the authentication state is retrieved from local storage and stored in the state. If the user is not authenticated, the application will redirect to the login page otherwise it will display the dashboard page.

import { useEffect, useState } from "react";
const Dashboard = () => {
const [authenticated, setauthenticated] = useState(null);
useEffect(() => {
const loggedInUser = localStorage.getItem("authenticated");
if (loggedInUser) {
setauthenticated(loggedInUser);
}
}, []);
if (!authenticated) {
} else {
return (
<div>
<p>Welcome to your Dashboard</p>
</div>
);
}
};
export default Dashboard;

Redirect user to login page using Navigate

The Navigate component replaced the Redirect component that was used in React Router v5. Import Navigate from react-router-dom.

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

To redirect unauthenticated users, use it as follows.

if (!authenticated) {
return <Navigate replace to="/login" />;
} else {
return (
<div>
<p>Welcome to your Dashboard</p>
</div>
);
}

The Navigate component is a declarative API. It relies on a user event, which in this case is an authentication to cause a state change and therefore cause the component to be re-rendered. Note that you are not required to use the replace keyword. Using it replaces the current URL instead of pushing it into the browser history.


Redirect user to another page using useNavigate()

The other option to perform redirects in React is the useNavigate() to hang up. This hook provides access to the imperative navigation API. Start by importing it from react-router-dom.

import { useNavigate } from "react-router-dom";

Redirect once the user is successfully authenticated in the handleSubmit() work like this:

const navigate = useNavigate();
const Login = () => {
const navigate = useNavigate();
const [username, setusername] = useState("");
const [password, setpassword] = useState("");
const [authenticated, setauthenticated] = useState(
localStorage.getItem(localStorage.getItem("authenticated") || false)
);
const users = [{ username: "Jane", password: "testpassword" }];
const handleSubmit = (e) => {
e.preventDefault();
const account = users.find((user) => user.username === username);
if (account && account.password === password) {
localStorage.setItem("authenticated", true);
navigate("/dashboard");
}
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
name="Username"
value={username}
onChange={(e) => setusername(e.target.value)}
/>
<input
type="password"
name="Password"
onChange={(e) => setpassword(e.target.value)}
/>
<input type="submit" value="Submit" />
</form>
</div>
);
};

In this example, once the user submits the form with the correct details, they are redirected to the dashboard.

When building apps, one of the goals is to give users the best experience. You can do this by taking the user back to the page they were on before by redirecting them to the login page. You can do this by passing -1 to navigate like this, navigate(-1). It acts the same as pressing the back button on your browser.

Routing in React

In this article, you learned how to redirect a user to another page in React using both the Navigate component and the useNavigate() to hang up. The article used a login form to show how you can redirect unauthenticated users from a protected page to the login page.

Post navigation

Smartwatch maker paid Huawei $0.29 million
CIBIL connection, registration and meaning of the CIBIL score: 3 important things to know

Categories

  • Website checker
  • Website file
  • Website login
  • Website maker
  • Website Store

asia pacific east africa email address forecast period growth rate market report market research market share market size middle east north america official website phone number press release united states

Recent Posts

  • Beginner’s Guide to Applying a Loan with the Controversial Lender: Citrus North

  • DSNY Enforcers File Discrimination and Wage Complaint

  • Social Login Tools Market Size 2028 – Global Industry Sales, Revenue, Price Trends & More – Shanghaiist

  • Sturm, Ruger & Company, Inc. to Release Second Quarter Results and File Quarterly Report on Form 10-Q on Wednesday, August 3 | New

  • European missile maker confirms data theft and denies network compromise

  • Delta app and website down or connection not working? You’re not alone

Archives

  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021
  • May 2021
  • April 2021
  • February 2021
  • December 2020

You may Missed

Website file

DSNY Enforcers File Discrimination and Wage Complaint

August 3, 2022
Sarah N. Randall
Website login

Social Login Tools Market Size 2028 – Global Industry Sales, Revenue, Price Trends & More – Shanghaiist

August 3, 2022
Sarah N. Randall
Website file

Sturm, Ruger & Company, Inc. to Release Second Quarter Results and File Quarterly Report on Form 10-Q on Wednesday, August 3 | New

August 2, 2022
Sarah N. Randall
Website maker

European missile maker confirms data theft and denies network compromise

August 2, 2022
Sarah N. Randall
Copyright © 2022 Blokland Prive Vakantiehuizen
Privacy Policy