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.
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.