Usually, when building web applications, login pages are used to protect private pages. For example, for a blogging platform, the dashboard may only be accessible to authenticated users. If an unauthenticated user tries to access that page, the application redirects them to the login page. Once they are logged in, they get access.

We will look at how you can redirect a user from a restricted page to a login page. We will also discuss how you can return the user back to the page they were on after logging in.

Create a React Application

In React Router v6, there are two ways you can use to redirect a user — the Navigate component and the useNavigate() hook.

To see how they work, first, create a React application using the create-react-app command.

        npx create-react-app react-redirect

Create a Login Page

You will need to create a Login page to authenticate users. For simplicity, you'll 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, the application compares the data to array data. If the user details are in the array, the application sets the authenticated state for that user to true.

Since you will be checking if the user is authenticated in the Dashboard component, you also need to store the authentication status somewhere that can be accessed by other components. This article uses local storage. In a real application, using React context would be a better choice.

Create a Dashboard Page

Create a file named Dashboard.js and add the following code to create the Dashboard component.

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

The dashboard should only be accessible to authenticated users only. Therefore, when users visit the dashboard page, first check whether they are authenticated and if they aren't, redirect them to the login page.

To do this, you'll need to set up the application routes using React router, so install react-router-dom via npm.

        npm install react-router-dom

Then, in index.js, create the routes.

        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 the Dashboard Page

Now that your application routes are set up, the next step is to make the dashboard route private. When the Dashboard component loads, it retrieves the authentication from the local storage and stores it in the state. It then checks if the user is authenticated. If they're authenticated, the application returns the dashboard page otherwise it redirects them to the login 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) {
  // Redirect
  } else {
    return (
      <div>
        <p>Welcome to your Dashboard</p>
      </div>
    );
  }
};

export default Dashboard;

Redirect User to Login Page Using Navigate

To redirect the user, you need to use the Navigate component. Note that this component replaced the Redirect component used in React Router v5.

Import Navigate from react-router-dom.

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

Then use it as follows to redirect unauthenticated users.

        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 authentication to cause a state change and consequently cause a component re-render. Note that you don't have to use the replace keyword. Using it replaces the current URL instead of pushing it to the browser's history.

Redirect User to Another Page Using useNavigate()

The other option for performing redirects in React is the useNavigate() hook. This hook provides access to the navigate imperative API. To use it, start by importing it from react-router-dom.

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

After login, redirect the user to the dashboard page using the handleSubmit() function as shown below:

        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.

Note that when creating applications, one of the goals is to give users the best experience. In this case, taking the user back to the page they were on before redirecting them to the login page improves user experience. You can do this by passing -1 to navigate like this, navigate (-1).

Routing in React

In this article, you learned how you can redirect a user to another page in React using both the Navigate component and the useNavigate() hook. Use this information to create an authentication flow for your own app where you redirect unauthenticated users from a protected page to the login page.