1. Preface
react-router
Library plays a crucial role in React application development. It is the core tool for implementing page routing management. It allows developers to accurately render corresponding components according to different URL paths, which is indispensable for building smooth and interactive single-page applications (SPAs). Through it, users can dynamically switch page content without frequently refreshing the entire page when browsing applications, greatly improving the user experience.
For example, many well-known React applications, such as the front-end of some large e-commerce platforms, online office software, etc., have used the help ofreact-router
To manage a variety of page routing, implement complex functional module switching and page navigation, so that users can easily and quickly shuttle between various functional pages.
Generally speaking, React-Router v6 requires React v16.8 or higher. Because React-Router v6 takes advantage of features such as React's Hooks, React v16.8 is the first version to introduce Hooks. Using an earlier version of React, it may cause React-Router to not work properly or some features are missing.
2. Installation
- Install using npm (recommended)
- Open the terminal and enter the React project directory.
- If the React project is not installed, you can create a new project using Create React App, etc.
- In the project directory, run
npm install react-router-dom
After the installation is successful, you can view itnode_modules
Is there a directoryreact-router-dom
Folders, or import related modules in code files (e.g.import { BrowserRouter } from'react-router-dom'
) Verify that the installation is correct without an error.
Install using yarn
- Open the terminal and enter the React project directory.
- run
yarn add react-router-dom
The command can be used after completion.
3. Basic use
Project React version: 18.3.1; react-router-dom version: 7.1.1.
Set up the routing infrastructure
In React application portal files (usuallyor
),use
BrowserRouter
(Based on browser history, URLs are more natural) orHashRouter
(Special deployment requirements or compatibility with old browsers) wraps the entire application. Ifmiddle:
import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; import { BrowserRouter as Router } from 'react-router-dom'; import App from './'; createRoot(('root')).render( <StrictMode> <Router> <App /> </Router> </StrictMode> );
Here willApp
Components wrapped inRouter
(BrowserRouter
in the alias ofApp
Components and their subcomponents can access routing-related functions.
Define routing and component associations
existApp
In components or other components,Route
Components define routing rules.
Define routes directly in the component
This method directly places the routing definition inside the component, which has intuitive advantages for small applications or when routing rules are relatively simple. Developers can clearly see the relationship between a certain component and a specific routing path at a glance, and the routing rules are closely integrated with the component, which is very suitable for the routing management within the component itself, especially when the component is an independent functional module, which can make the module functions more cohesive.
import React from 'react'; import { Route } from 'react-router-dom'; import Home from './Home'; import About from './About'; const App = () => { return ( <div> {/* The Route component defines the route, and exact matches exactly to ensure that the path is completely '/' is rendered. The Home component is not rendered when accessing '/about'. Access the '/' rendering Home component, and access the '/about' rendering About component. */} <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> </div> ); } export default App
However, as the application scale gradually increases and routing rules become complicated, this writing method will expose obvious shortcomings. For example, in a large e-commerce application, if hundreds of routes are written in the App components, the code will become extremely bloated, and maintenance operations such as finding components associated with specific routes and modifying routing parameters will become extremely cumbersome, and the readability of the code will be greatly reduced, which is not conducive to subsequent development and maintenance.
Define a single routing table
Creating a single routing table can centrally manage all routing rules, which is especially important for large application development. During the development process, developers can clearly view all routing paths, corresponding components, and possible routing parameters in one file. Moreover, the routing table has good reusability. For example, in different layout components (such as layouts with different sidebars), this unified routing table can be referenced to achieve the same routing function without repeated configuration. At the same time, when it is necessary to modify the routing rules, you only need to operate in the routing table file, without modifying them one by one in the components that use routing, greatly improving the development efficiency and maintainability of the code. With the continuous development of applications, it is also very convenient to add new routes, and for routing middleware (such as permission verification, only logged-in users can access certain routes) and other functions, it can also be configured more conveniently in the routing table.
createFile defines routing tables and centrally manages routing rules.
import { lazy } from 'react'; // lazy is used to set the route lazy loadingconst Home = lazy(() => import('@/pages/Home')); const About = lazy(() => import('@/pages/About')); const Router = [ { path: '/', element: <Home /> }, { path: '/about', element: <About /> }, // Set 404 page { path: '*', element: <NotFound /> } ]; export default Router
Then use this routing table in the App component:
import router from './router'; import { Suspense } from 'react'; import { useRoutes } from 'react-router-dom'; function App() { // useRoutes Generate corresponding routing elements according to the incoming routing configuration, which means that the component tree structure should be rendered. const element = useRoutes(router); // Suspense sets a page redirect loading prompt, and the component is displayed with fallback specified content when loading. return <Suspense fallback={'loading...'}>{element}</Suspense>; } export default App
This method is suitable for large applications, with good reusability, convenient modification and routing, and is also convenient to configure middleware (such as permission verification).
Create a navigation link
Use Link components to create navigation links inside the application. It is different from traditional tags. When a user clicks on a Link component, it will not cause the entire page to refresh, but will update the URL through JavaScript and trigger the corresponding component rendering to achieve seamless navigation within a single-page application.
import React from 'react'; import { Link } from 'react-router-dom'; const Navigation = () => { return ( <nav> {/* The Link component to property specifies the navigation target path, click the 'Home' link to navigate to the root path to render the Home component, Click the 'About' link to navigate to the '/about' path to render the About component. */} <Link to="/">Home</Link> <Link to="/about">About</Link> </nav> ); } export default Navigation
IV. Core components and functions
BrowserRouter and HashRouter
- BrowserRouter: Based on the HTML5 browser history API, the URL format is natural and there is no "#" symbol. For example, the URL of the e-commerce product details page can be "/products/123", which is conducive to SEO.
- HashRouter: Use URL hashing to manage routing, suitable for old browsers or servers that do not support HTML5 History API, and deployments perform well on simple static servers.
hash and history
Route Component
Route
Components are core, define routing rules, and associate URL paths with components.
import React from 'react'; import { Route, BrowserRouter as Router } from 'react-router-dom'; import Home from './Home'; import About from './About'; const App = () => { return ( <Router> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> </Router> ); } export default App
exact
Attributes match paths exactly to avoid mis-rendering.
Link Components
With tradition<a>
The tag is different, click not to refresh the page, and update the URL triggers component rendering.
import React from 'react'; import { Link } from 'react-router-dom'; const Navigation = () => { return ( <nav> <Link to="/">Home</Link> <Link to="/about">About</Link> </nav> ); } export default Navigation
Switch components
Pack a groupRoute
Component, only render the first match successfullyRoute
, prevent multiple components from rendering at the same time.
import React from 'react'; import { Route, Switch, BrowserRouter as Router } from 'react-router-dom'; import Home from './Home'; import About from './About'; import NotFound from './NotFound'; const App = () => { return ( <Router> <Switch> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> <Route component={NotFound} /> </Switch> </Router> ); } export default App
In this example, if there is no Switch component, both the NotFound component and the previous component that may partially match (such as the Home component) may be rendered when the user accesses a non-existent path. With the Switch component, only the NotFound component will be rendered because the previous routes have not matched successfully.
5. Routing parameters and nested routing
Routing parameters
React-Router
Allows the definition of parameters in the routing path. For example, in a list, the route of the content details page can be defined as/articles/:id
,in:id
is a parameter that represents the unique identifier for the details. In the component, it can be passedGet this parameter.
import React from 'react'; import { Route, BrowserRouter as Router } from 'react-router-dom'; const ArticleDetail = props => { const articleId = ; // Obtain article details and render according to articleId return ( <div> <h1>Article Detail {articleId}</h1> </div> ); } const App = () => { return ( <Router> <Route path="/articles/:id" component={ArticleDetail} /> </Router> ); } export default App
User access/articles/123
hour,articleId
It is "123".
Nested routing
Complex applications have nested routing situations, such as the e-commerce product details page has a comment section.
import React from 'react'; import { Route, BrowserRouter as Router, Switch } from 'react-router-dom'; import ProductDetail from './ProductDetail'; import ProductReviews from './ProductReviews'; const App = () => { return ( <Router> <Switch> <Route path="/products/:id" component={ProductDetail}> <Route path="/products/:id/reviews" component={ProductReviews} /> </Route> </Switch> </Router> ); } export default App
When accessing "/products/123/reviews", render firstProductDetail
Components, then render in appropriate locations inside themProductReviews
Components.
Deepening of nested routing levels and expanding application scenarios
Taking enterprise-level applications as an example, display multi-layer nested routing scenarios such as department details pages, employee list pages, employee personal details pages and employee performance pages, and implement orderly page switching through reasonable configuration.
import React from 'react'; import { Route, BrowserRouter as Router, Switch } from 'react-router-dom'; const DepartmentDetail = props => { return ( <div> <h1>Department Detail</h1> {/* Display department related information */} <Route path={`${}/employees`} component={EmployeeList} /> </div> ); } const EmployeeList = props => { return ( <div> <h2>Employee List</h </div> {/* Show employee list */} <Route path={`${}/:employeeId`} component={EmployeeDetail} /> <Route path={`${}/:employeeId/performance`} component={EmployeePerformance} /> </div> ); } const EmployeeDetail = props => { const { employeeId } = ; return ( <div> <h3>Employee Detail - ID: {employeeId}</h3> {/* Show personal details of employees */} </div> ); } const EmployeePerformance = props => { const { employeeId } = ; return ( <div> <h3>Employee Performance - ID: {employeeId}</h3> {/* Show employee performance related information */} </div> ); } const App = () => { return ( <Router> <Switch> <Route path="/departments/:departmentId" component={DepartmentDetail} /> </Switch> </Router> ); } export default App
Through such complex examples, we can better understand how nested routing plays a role in building large-scale, feature-rich applications, and how to design and configure multi-layer nested routing structures according to actual business needs, so as to better deal with complex page relationships and functional module divisions
6. Programming navigation
removeLink
Component, React-Router supports programmatic navigation, throughhistory
Object implementation, can be used in componentsObtain (component needs to be passed
Route
component rendering).
import React from 'react'; import { Route, BrowserRouter as Router, useNavigate } from 'react-router-dom'; const MyComponent = props => { const Navigate = useNavigate(); const handleClick = () => { Navigate('/about'); } return ( <div> <button onClick={handleClick}>Go to About</button> </div> ); } const App = () => { return ( <Router> <Route path="/" component={MyComponent} /> </Router> ); } export default App
Click the button and callhandleClick
Function, navigate to the "/about" path, suitable for internal logical navigation such as successful form submission.
7. Routing permissions
Routing table
import { lazy } from 'react'; import Auth from './AuthRoute'; const Home = lazy(() => import('@/pages/Home')); const About = lazy(() => import('@/pages/About')); const List = lazy(() => import('@/pages/List')); const User = lazy(() => import('@/pages/User')); const NotFound = lazy(() => import('@/pages/NotFound')); const Router = [ { path: '/', element: <Home /> }, { path: '/about', element: <About /> }, { path: '/app/', element: ( // Custom permission components <Auth> <BasicLayout /> </Auth> ), errorElement: <NotFound></NotFound>, children: [ { path: 'list', element: <List /> }, { path: 'list/user', element: <User /> } ] }, // Set 404 page { path: '*', element: <NotFound /> } ]; export default Router
Permissions component
import { useEffect, useRef } from 'react'; import { useNavigate, useLocation } from 'react-router-dom'; import { message } from 'antd'; import useUpdateEffect from '@/components/useUpdateEffect'; export default function Auth({ children }: any) { const location = useLocation().pathname; const didMountRef = useRef(false); const Navigate = useNavigate(); const token = ('token'); useEffect(() => { if () { if (!token) { ('You are not logged in, will jump'); setTimeout(() => { Navigate('/login'); }, 1000); } } else { = true; } }, [token]); return children; }
404 pages
import React from 'react'; const CommonLine = props => ( // Change according to personal needs <div>This page was not found</div> ); export default CommonLine
This is the article about React Router one-stop guide: From getting started to mastering and mastering routing and permission control. For more related React Router routing and permission control, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!