“This is the first day of my participation in the First Challenge 2022. For details: First Challenge 2022”

The React Router is one of the most popular libraries in the React ecosystem, with more than 600 downloads per week on NPM and 45.2K star ratings on Github. The React Router has gone through several iterations and significant changes. The latest version is 6.0.2, which is a big change compared with the previous 5.x version. Both usage and performance have been significantly improved. This article will also use the way of comparing the old version with the new version to make you get started with the new usage as soon as possible

This article will focus on the following 6 points to learn react-router@6:

  1. <Route/>Use change
  2. <Switch/>Replace with<Routes/>
  3. Nested routines are written in a new way
  4. How to implement route redirection
  5. How to implement route redirection
  6. Use of new Hook

<Route/>Use change

The
component has changed a lot, removing component and render attributes and replacing them with element attributes, so it is incompatible with previous versions of the code

    The usage / / 5. X
    <Route path="/home" component={Home} />
    <Route path="/login" render={()= ><Login/>} / >

    The usage / / 6. X
    <Route path="/home" element={<Home/>} / >
    <Route path="/login" element={<Login/>} / >
Copy the code

<Switch/>Replace with<Routes/>

The v6 version removes the
component and replaces it with
. In addition to replacing the function of the
component, some changes have been made. For example, all

must be wrapped in
otherwise an error will be thrown

    The usage / / 5. X
    <Switch>
        <Route path="/home" component={Home} />
        <Route path="/login" component={Login} />
    </Switch>

    The usage / / 6. X
     <Routes>
        <Route path="/home" element={<Home/>} / ><Route path="/login" element={<Login/>} / ></Routes>
Copy the code

Embedded routines by

React-router v6 supports multiple nested routines:

  • The first way to write it is to continue the V5 version and keep the original component structure

    This is suitable for refactoring projects, where you can transition to v6 without changing too much code

        // App.jsx
        <Routes>
            <Route path="/home" element={<Home/>} / >
            <Route path="/user/*" element={<User/>} / >
        </Routes>
    
        // User.jsx
        <Routes>
            <Route path="profile" element={<UserProfile/>} / ><Route path=":/id" element={<UserDetail/>} / ></Routes>
    Copy the code

    In app.jsx, the path attribute of

    must end with an asterisk (path=”/user/*”), and the path of the child component user.jsx does not need to start with a /

    If the nested
    path attribute does not start with a /, it is relative to its parent path. The advantage of this is that it is much easier to implement nested routines, and it is easier to combine complex routes and layouts, so there is no need to write the entire path as in V5. Mom no longer has to worry about me writing the wrong address

  • The second way is to write all
    together and use
    to display the Route component

        // App.jsx
        <Routes>
            <Route path="/home" element={<Home/>} / >
            <Route path="/user" element={<User/>} ><Route path="profile" element={<UserProfile/>} / ><Route path=":/id" element={<UserDetail/>} / ></Route>
        </Routes>
    
        // User.jsx
        <Outlet/>
    Copy the code

    This gives us a clearer view of the routing structure, allows us to better manage our routing, and
    allows us to more precisely place nested routing components where they need to be displayed.
    and
    are rendered to the location of
    in the user.jsx file when routing matches.)

    If you want to render a Route by default when the user accesses /user, you can add the index attribute to the
    component to make it the default Route, as follows: Render the
    component content when the user accesses /user

        // App.jsx
        <Routes>
            <Route path="/home" element={<Home/>} / >
            <Route path="/user" element={<User/>} ><Route path="profile" element={<UserProfile/>} index />
                <Route path=":/id" element={<UserDetail/>} / ></Route>
        </Routes>
    Copy the code
  • Third, use useRoutes() to configure the route

    Using useRoutes to configure Routes has the same effect as
    , except that this method uses javascript to generate Routes, does not depend on JSX, and returns the routing component tree of the corresponding structure. Do you have any?

        function App(){
            // The following method has the same effect as the second one
            const element = useRoutes([
                {path:'/home'.element:<Home/>},
                {
                    path:'/user'.element:<User/>,
                    children:[
                        {path:'profile'.element:<UserProfile/>},
                        {path:':/id'.element:<UserDetail/>}},]])return element
        } 
    Copy the code

Each of the above three methods has its own advantages, and developers can choose one of them to implement your nesting method according to their own needs

redirect

The new version of the React – Router removes the Redirect/> component, but can use the new
component with the
component to achieve the Redirect effect

    <Routes>
        <Route path="/home" element={<Home/>} / >
        <Route path="/" element={<Navigate to="/home"/>} ></Routes>
Copy the code

Routing hop

After the route is configured, it is inevitable to redirect the page. However, the history object is removed from the new version of The React – Router, so history (including useHistory hook) of the V5 version cannot be used. We can use the following two methods to redirect the page

  • Jumping to or
    is almost the same as the previous version, the only difference is that the
    component is highlighted (highlighted using the style or className callback function, as follows).

        / / the v5 version
        <NavLink to="/home" activeStyle={{color:'#f00'}} > home page < / NavLink ><NavLink to="/home" activeClassName="active">Home page</NavLink>
    
        / / v6 version
        <NavLink to="/home" style={({isActive})= >(isActive? {color: '# f00'}, {})} > home page</NavLink>
        <NavLink to="/home" className={({isActive})= >isActive? 'current' : ' '} > home page</NavLink>
    Copy the code

    PS:
    already has an active class for highlighting by default, which can be used directly without additional Settings

  • Sometimes we can’t use useNavigate() to jump to a different page based on the value of an Ajax request. In this case, we have to use JS to jump to a different page. Although the new version of react router has removed the history object, However, useNavigate() hook is provided to realize route jump, and the usage method is as follows

       import { useNavigate } from "react-router-dom";
       let navigate = useNavigate();
       navigate(`/home`);
    
       // Jump without keeping browsing records
       navigate(`/home`, {replace:true});
    
       // return to the previous page
       navigate(-1)
    
       // Object jump
       navigate({
           pathname:'/home'
       })
    Copy the code

    Note that in v6 react-Router, if a jump path does not start with a slash, it is a relative path, relative to its parent route path. This setting gives us better control over the jump

Routing and the cords

We all know that you can implement special functions by passing parameters to the target page when routing jumps, but the new react-Router has removed history, location, and match from the props, as well as withRouter higher-order components. So you cannot use the old version of the way to participate in receiving, the new version of the usage is as follows

  • Search the parameter

        let navigate = useNavigate();
        navigate(`/home? page=1&size=10`);
        navigate({
            pathname:'/home'.search:'page=1&size=10'
        });
    Copy the code

    It is also very simple to receive parameters in the corresponding component, using useSearchParams hook to receive, and get URLSearchParams object and set the search parameter function composed of data

        function Home(){
            const [searchParams,setSearchParams] = useSearchParams()
            searchParams.get('page');/ / 1
            searchParams.get('size');/ / 10
            return (
                <div>Home page</div>)}Copy the code
  • Dynamic route parameter transmission

        <Route path="/user" element={<User/>} ><Route path=":/id" element={<UserDetail/>} / >
        </Route>
    
    Copy the code

    After the preceding routes are configured, you can use useParams hook in the
    component to obtain the ID 123 when switching to /user/123

        function UserDetail(){
            const {id} = useParams()
            return (
                <div>id:{id}</div>)}Copy the code
  • The state parameter can be passed through ,
    , or useNavigate. The usage is as follows:

        <Link to="/home" state={{idx:1.key:'qf'</Link> navigate('/home', {state: {idx:1.key:'qf'}})
    Copy the code

    Get the state value from the useLocation hook in the home page component

        function Home(){
            const {state} = useLocation();
            state.idx; / / 1
            state.key; // qf
            return (
                <div>Home page</div>)}Copy the code

other

In addition, the React route also supports other functions such as SSR server rendering. Due to space limit, I will not elaborate on these functions here. Please follow me if you are interested.

conclusion

That’s all for this article, which gives you an overview of the new version of React – Router6 so you can use it in your projects.

See the react to the router’s website documents: reactrouter.com/docs/en/v6