Detailed explanation of the use of react router V6

Posted by ksb24930 on Tue, 01 Mar 2022 07:22:19 +0100

  • The Remix team released its first v6.1 in June 2020 0.0-beta. The 0 version of react router also indicates the official start of the V6 version. Compared with the V5 version, there are many upgrades.
  • This article will explain the use of react router in detail in combination with the characteristics of V6 and how to upgrade V6 in V5.
  • (version used: V6.0.2 stable version)

1, Basic usage

Installation method of react Router:

npm: npm install react-router-dom

yarn: yarn add react-router-dom

  • At present, the original react router library has been abandoned by the government since 5 and is uniformly named react router dom
usage method
  • React router itself is a component in react development, so it basically follows the relevant principles of component development. Here, create react app is used to create a basic demo project to demonstrate the use process.
  1. Create demo create react app my first react

Install the react router component

  1. Enable global routing mode

There are two common routing modes for global routing: HashRouter and BrowserRouter
HashRouter: the hash(#) part is used in the URL to create a route, similar to www.example.com/#/ BrowserRouter: the URL uses real URL resources
The principle and implementation of HashRouter will be described in detail in subsequent articles. Here, we use BrowserRouter to create a route

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom';

ReactDOM.render(
 <React.StrictMode>
   <BrowserRouter>
     <App />
   </BrowserRouter>
 </React.StrictMode>,
 document.getElementById('root')
);

reportWebVitals();

In this way, we can access / access this component when we visit or npm run start. You can run the specific effects by yourself

  1. Routing function
    Route components and hooks are commonly used in the react router V6 version. For others that are not commonly used, you can see the introduction on the official website
Component nameeffectexplain
<Routers>A set of routesInstead of the original < Switch >, all sub routes are represented by the basic Router children
<Router>Basic routingThe Router can be nested to solve the strict mode in the original V5. The differences between it and V5 will be described in detail later
<Link>Navigation componentsJump to use in the actual page
<Outlet/>Adaptive rendering componentAutomatically select components according to the actual route url
hooks nameeffectexplain
useParamsReturns the current parameterRead parameters according to path
useNavigateReturns the current routeReplace useHistory in V5
useOutletReturns the element generated according to the route
useLocationReturns the current location object
useRoutesLike the routes component, it is only used in js
useSearchParamsUsed to match the URL? Subsequent search parameters

App.js

  • Here we create two components, Home and about, and then register / and about respectively. There is also a Link on each page for navigation

    import './App.css';
    import { Routes, Route, Link } from "react-router-dom"
    function App() {
     return (
       <div className="App">
         <header className="App-header">
           <Routes>
             <Route path="/" element={<Home />}></Route>
             <Route path="/about" element={<About />}></Route>
           </Routes>
         </header>
       </div>
     );
    }
    function Home() {
     return <div>
       <main>
         <h2>Welcome to the homepage</h2>
       </main>
       <nav>
         <Link to="/about">about</Link>
       </nav>
     </div>
    }
    function About() {
     return <div>
       <main>
         <h2>Welcome to the about page</h2>
       </main>
       <nav>
         <ol>
           <Link to="/">home</Link>
           <Link to="/about">about</Link>
         </ol>
    
       </nav>
     </div>
    }
    export default App;
    
    

    After operation

    At this point, the simplest routing demo is running normally.

  1. Nested Route

Nested routing is a major upgrade of V6 version to the previous version. Using nested routing will be recognized intelligently

function App() {
 return (
   <Routes>
     <Route path="user" element={<Users />}>        
         <Route path=":id" element={<UserDetail />} />        
         <Route path="create" element={<NewUser />} />      
     </Route>
   </Routes>
 );
}

When accessing / user/123, the component tree will look like this

<App>
   <Users>
       <UserDetail/>
   </Users>
</App>

When / user/create is accessed, the component tree will look like this

<App>
  <Users>
      <NewUser/>
  </Users>
</App>

If only internal components are modified, you can also use < outlet / > to directly implement it, as shown below

function App() {
 return (
   <Routes>
     <Route path="user" element={<Users />}>        
         <Route path=":id" element={<UserDetail />} />        
         <Route path="create" element={<NewUser />} />      
     </Route>
   </Routes>
 );
}

function Users() {
 return (
   <div>
     <h1>Users</h1>
     <Outlet />
   </div>
 );
}
  1. index routing

The index attribute is used to specify the default route by adding the index attribute when the nested route has multiple sub routes but cannot confirm which sub route to render by default

function App() {
 return (
   <Routes>
     <Route path="/" element={<Layout />}>        
         <Route index element={<About />} />        
         <Route path="user" element={<User />} />        
         <Route path="about" element={<About />} />      
     </Route>
   </Routes>
 );
}
Copy code

In this way, < outlet / > will render the About component by default when accessing /

  1. Routing wildcard
  • The whole react router supports the following wildcards
/groups
/groups/admin
/users/:id
/users/:id/messages
/files/*
/files/:id/*

Note that the following regularization methods are not supported in V6

/users/:id?
/tweets/:id(\d+)
/files/*/cat.jpg
/files-*

The * here can only be used after / and cannot be used in the middle of the actual path

For NotFound routing, you can use * instead

function App() {
 return (
   <Routes>
     <Route path="/" element={<Home />} />      
     <Route path="dashboard" element={<Dashboard />} />      
     <Route path="*" element={<NotFound />} />    
   </Routes>
 );
}
  1. Get parameters useParams and useSearchParams

Assume existing App routing

function App() {
    return (
      <Routes>
        <Route path="user" element={<Users />}>       
  	      <Route path=":id" element={<UserDetail />} />       
  	      <Route path="create" element={<NewUser />} />     
        </Route>
      </Routes>
    );
}

Then use useParams to obtain the corresponding parameters in UserDetail

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

export default function UserDetail() {
 let params = useParams();
 return <h2>User: {params.id}</h2>;
}

useSearchParams is relatively complex. It returns a current value and a set method

let [searchParams, setSearchParams] = useSearchParams();

You can use searchparams Get ("id") to get parameters, and setSearchParams({"id": 2}) can also be used to change the route in the page, so that when accessing http://URL/user?id=111 You can get and set the path

  1. useNavigate

useNavigate is a new hook that replaces useHistory in V5. Its usage is similar to useHistory and it is lighter to use as a whole. Its declaration method is as follows:

declare function useNavigate(): NavigateFunction;

interface NavigateFunction {
 (
   to: To,
   options?: { replace?: boolean; state?: State }
 ): void;
 (delta: number): void;
}
 //js writing method
 let navigate = useNavigate();
 function handleClick() {
   navigate("/home");
 }
 //Component writing
 function App() {
    return <Navigate to="/home" replace state={state} />;
 }
 //Replace the original go, goback and goForward
<button onClick={() => navigate(-2)}>
   Go 2 pages back
 </button>
 <button onClick={() => navigate(-1)}>Go back</button>
 <button onClick={() => navigate(1)}>    Go forward  </button>
 <button onClick={() => navigate(2)}>    Go 2 pages forward  </button>

2, Difference from V5

1. Replace < Switch > with < routes > children

V5 writing method:

 function App() {
   return (
     <Switch>
       <Route exact path="/">
         <Home />
       </Route>
       <Route path="/about">
         <About />
       </Route>
       <Route path="/users/:id" children={<User />} />     
     </Switch>
   );
 }

V6 writing method

 function App() {
   return (
     <Routes>
       <Route index path="/" element={<Home />} />      
	       <Route path="about" element={<About />} />       
	       <Route path="/users/:id" element={<User />} />     
       </Routes>
   );
 }

2. Remove the < Redirect > in the Switch and replace it with the Redirect in the react router DOM, or implement it with < navigate >

V5 writing method:

 <Switch>
   <Redirect from="about" to="about-us" />
 </Switch>

V6 writing method:

 <Route path="about" render={() => <Redirect to="about-us" />}
 

3. < link to > support relative position

The to attribute of V5 version only supports absolute position. For example, < lint to = "me" > means < lint to = "/ me" >. If you are in the Users component at that time, you need < lint to = "/ Users / me" >. In V6, Link supports relative position by default, that is, < lint to = "me" > is equivalent to < lint to = "/ Users / me" > in the Users component, and supports'... 'and'. ' Equal relative path writing.

// If your routes look like this
<Route path="app">
<Route path="dashboard">
 <Route path="stats" />
</Route>
</Route>

// and the current URL is /app/dashboard (with or without
// a trailing slash)
<Link to="stats">               => <a href="/app/dashboard/stats">
<Link to="../stats">            => <a href="/app/stats">
<Link to="../../stats">         => <a href="/stats">
<Link to="../../../stats">      => <a href="/stats">

4. Use useNavigate instead of useHistory

You can refer to useNavigate above, which will not be repeated here

3, Summary

The V6 version of react router upgrades the original nested route writing method, and re implements useNavigate to replace useHistory, which is better understood on the whole. Of course, there are other properties and methods that have not been introduced. If you have other things you want to know, you can reply to me to add.

Reference link:

https://reactrouter.com/docs/en/v6/upgrading/v5
https://reactrouter.com/docs/en/v6/getting-started/overview

Topics: React