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.
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.
Before you begin, please make sure:
<code class="language-bash">npm install react-router-dom</code>
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.
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>
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>
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 (/).
<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>
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>
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.
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!