The use of React Router routing

1. Download

//Applicable to both js and ts
npm i --save react-router-dom @types/react-router-dom

2. Use

RouterProvider and createBrowserRouter are introduced in react-router-dom. The createBrowserRouter function is an array. The elements of the array are objects, which store routing information. The two most important attributes are path and element. path is a string type attribute that specifies the URL address matched by the current routing rule. Routing rules can be described using placeholders, optional parameters, and regular expressions. element is a property of a React component that specifies the component to be rendered by the current routing rule. A “/*” route is configured at the end of the array. The function is that all addresses other than registered routes entered will match this route and the components corresponding to this route will be displayed.

createBrowserRouter and RouterProvider are two helper functions used to create and provide BrowserRouter objects. BrowserRouter is the core object that defines routing in React Router. It is responsible for processing events such as history records, jump links, buttons, etc., and loading the corresponding element components based on the current URL matching routing rules. RouterProvider is a React component that can inject BrowserRouter objects into the React component tree and enable the entire React application to access and use BrowserRouter.

3. Route jump

In the user’s use, it is impossible to enter the routing address in the address bar, but to click on a certain control to jump, which requires jumping between routes to switch pages.

When specifying the rendering component of the route, you can import the component and use the component as the value of element. In this case, the performance is not very good when there are many components, because the user may only browse a few of them, but all components are imported and run. After doing it once, it will be useless. At this time, you can use lazy loading and import according to the routing situation.

//routing part
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from "./App"
import {createBrowserRouter,RouterProvider} from 'react-router-dom'

let load = (Com)=><React.Suspense fallback={<div>Loading...</div>}><Com></Com></React.Suspense>
const router = createBrowserRouter([
    {
        path:'/',
        element: <App></App>
    },
    {
        path:'/login',
        element: load(React.lazy(()=>import('./Box1.jsx')))
    },
    {
        path:'/detail',
        element: load(React.lazy(()=>import('./detail.jsx')))
    },
    {
        path:'/discovery',
        element: load(React.lazy(()=>import('./discovery.jsx')))
    },
    {
        path:'/discovery2/:dt',
        element: load(React.lazy(()=>import('./discovery2.jsx')))
    },
    {
        path:'/*',
        element: <div>404 NOT Found</div>
    },
])
ReactDOM.createRoot(document.getElementById('root')).render(<RouterProvider router={router} />)

However, the result of lazy loading cannot be directly used as an attribute of element. It needs to be processed by a custom function to return a jsx object. But this object must be wrapped with react’s Suspense component, otherwise the error in the above figure will appear when routing. React.Suspense is a component introduced in React version 16.6. It is mainly used to solve the problem of lazy loading of components. Accepts a fallback attribute, which represents the fallback interface that needs to be rendered when waiting for the awaited component to be loaded, usually a loading animation or placeholder.

React routing jumps are similar to Vue routing jumps. There are two types: using label jumps and js programmatic jumps. The Link component and the useNavigate hook function are both functional tools for implementing navigation in React Router. The Link component is suitable for creating navigation links in JSX, while useNavigate is suitable for programmatic navigation inside the component.

import React from 'react'
import { Link,useNavigate } from 'react-router-dom'

export default function App() {
  let nav = useNavigate()
  let fn = ()=>{
    nav('detail')
  }
  let fm = ()=>{
    nav({pathname:'discovery'})
  }
  return (
    <div>
        <h2>All products</h2>

        {/* 1. Link label jump */}
        <Link to={'detail'}>Go to detail page</Link><br />
        <Link to='discovery'>Go to discovery page</Link><br />
        <Link to={<!-- -->{pathname:'login'}}>Go to login page</Link><br />

        {/* 2. Programmatic jump */}
        <button onClick={fn}>Jump to details page</button>
        <button onClick={fm}>Jump to discovery page</button>
    </div>
  )
}

4. Route value transfer

1. Link tag

You can directly splice question marks after the route, or add an attribute search to the object where pathname is located. The value is of string type. The question mark can be written or not, and the browser will automatically complete it in the address bar.

2. Programmatic value transfer

Question marks are spliced directly after the route; the variable receiving the return value of the useNavigate function is passed to the first parameter object, the value of the state attribute is the object type, and inside is the value to be passed; add another attribute search to the object where the pathname is located, and the value is a character String, question mark plus the value to be passed; dynamic routing parameters are passed with slashes to connect the passed values. The path is different when registering dynamic routing – “path:’/discovery2/:dt'”, the dt attribute is customized, The value is the passed value.

import React from 'react'
import { Link,useNavigate } from 'react-router-dom'

export default function App() {
  let nav = useNavigate()
  let fm = ()=>{
    //state parameter: the passed value is stored in useLocation().state
    // nav({pathname:'discovery'},{state:{name:'tom'}})

    nav('discovery?name=tom &age=23')

    // query parameters (query parameters): the passed value is stored in useLocation().search
    // nav({pathname:'discovery',search:'?name=tom & amp;age=21'})

    //Dynamic routing parameters: the passed values are stored in useParams
    // nav({pathname:'discovery2/2024'})
  }
  return (
    <div>
        <Link to={'detail'}>Go to detail page</Link><br />
        {/* Direct question mark splicing---------the passed value is saved in useLocation().search */}
        <Link to='discovery?id=13'>Go to discovery page</Link><br />

        {/* Add another attribute search, the value is a string, the question mark is optional, the browser will automatically add it in the address bar */}
        <Link to={<!-- -->{pathname:'login',search:'name="tom"'}}>Go to login page</Link><br />

        <button onClick={fm}>Jump to discovery page</button>
    </div>
  )
}

To obtain routing information, you need to introduce the useLocation hook function, and the return value of the hook contains routing-related information. The passed value is either stored in the search attribute or in the state attribute. If it is dynamic routing, it is another hook function useParams.