Home > Web Front-end > JS Tutorial > How to Create Protected Routes with React and React Router DOM

How to Create Protected Routes with React and React Router DOM

Barbara Streisand
Release: 2025-01-24 02:29:09
Original
675 people have browsed it

Cómo Crear Rutas Protegidas con React y React Router DOM

When building web applications using React, we often need to restrict access to certain routes and only allow access to authenticated users. This article will explain how to create a protected route using React, react-router-dom and the Outlet component, and demonstrate how to verify whether the user is an administrator based on the value stored in localStorage.

What is protected routing?

Protected routes refer to pages that can only be accessed by users who meet specific conditions (such as being authenticated or having specific permissions, such as administrator permissions). If these conditions are not met, the user will be redirected to another page, such as a login page.

Prerequisites

Before you begin, please make sure:

  • React has been configured in the project.
  • React-router-dom installed:
<code class="language-bash">npm install react-router-dom</code>
Copy after login

Example: Protected routing with admin verification

This example will verify that the user is authenticated as an administrator by checking the value in localStorage. If not an administrator, redirect them to the login page.

  • Routing configuration

First, configure the application’s main route.

<code class="language-javascript">import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Login from "./Login";
import Dashboard from "./Dashboard";
import ProtectedRoute from "./ProtectedRoute";

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Login />} />
        <Route element={<ProtectedRoute />} path="/dashboard/*">
          <Route index element={<Dashboard />} /> {/*  添加index路由处理/dashboard */}
        </Route>
      </Routes>
    </Router>
  );
}

export default App;</code>
Copy after login
  • Create ProtectedRoute component

This component verifies that the user is authenticated as an administrator before rendering the protected route. If not, redirect it to the login page.

<code class="language-javascript">import React from "react";
import { Navigate, Outlet } from "react-router-dom";

const ProtectedRoute = () => {
  // 从localStorage中检查用户是否为管理员
  const isAdmin = localStorage.getItem("role") === "admin";

  return isAdmin ? <Outlet /> : <Navigate to="/" />;
};

export default ProtectedRoute;</code>
Copy after login

Code explanation:

localStorage.getItem("role"): Get the user role stored in localStorage. If the role is "admin", the Outlet component is rendered, which represents the content of the protected route. If not, use the Navigate component to redirect the user to the root path (/).

  • Create a login page (Login) This page simulates the basic login process and stores the user role in localStorage.
<code class="language-javascript">import React from "react";
import { useNavigate } from "react-router-dom";

function Login() {
  const navigate = useNavigate();

  const handleLogin = () => {
    // 模拟登录并保存用户角色
    localStorage.setItem("role", "admin");
    navigate("/dashboard");
  };

  return (
    <div>
      {/* 登录表单 */}
      <button onClick={handleLogin}>登录</button>
    </div>
  );
}

export default Login;</code>
Copy after login
  • Create Dashboard page

Dashboard page is a protected route and can only be accessed by users with administrator role.

<code class="language-javascript">import React from "react";

function Dashboard() {
  return (
    <div>
      <h1>仪表盘</h1>
      <p>这是受保护的页面内容。</p>
    </div>
  );
}

export default Dashboard;</code>
Copy after login

Example process

User access application:

If you are not logged in, you will see the login page (/). After logging in as an administrator, the role will be stored in localStorage and redirected to Dashboard (/dashboard). In the Dashboard, protected content (statistics and configuration) is displayed.

If a user attempts to access the Dashboard directly without admin rights, they will automatically be redirected to the login page.

Summary

Protected routing is critical for applications that handle users and permissions. Using the React Router DOM, Outlet component, and browser storage (such as localStorage), we can implement a basic access restriction system. This approach is great for small applications or learning projects, but in larger projects, a stronger authentication solution is recommended.

If you have any questions, please leave a message in the comment area! ?

The above is the detailed content of How to Create Protected Routes with React and React Router DOM. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template