This article aims to be concise and help you get started quickly with react-router-dom

The installation

Enter the following command to install:

// npm
npm install react-router-dom

// yarn
yarn add react-router-dom
Copy the code

React-router Indicates related labels

The react-Router components are as follows:

import { 
  BrowserRouter,
  HashRouter,
  Route,
  Redirect,
  Switch,
  Link,
  NavLink,
  withRouter,
} from 'react-router-dom'
Copy the code

Simple route jump

Realize a simple one – level route jump

import { 
    BrowserRouter as Router, 
    Route, 
    Link 
} from 'react-router-dom'
import Home from './home'
import About from './about'

function App() {
  return (
    <div className="App">
      <Router>
        <Link to="/home" className="link">Jump to Home page</Link>
        <Link to="/about" className="link">Jump to About page</Link>
        <Route path="/home" component={Home}/>
        <Route path="/about" component={About}/>
      </Router>
    </div>
  );
}

export default App;
Copy the code

The effect is as follows:

Summary of main points:

  1. RouteThe component must be inRouterComponents,
  2. LinkThe component’stoProperty is the path to jump to after being clicked
  3. RouteSet up thepathAttributes are withLinkOf the labeltoAttribute matching;componentAttribute saidRouteThe component object rendered after the component matches successfully

Nested routines by jump

The React route matching hierarchy is sequential

For example, in the App component, set the matching path of two routing components, respectively /home and /about, as follows:

import { 
  BrowserRouter as Router, 
  Route, 
  Link,
} from 'react-router-dom'
import Home from './home'
import About from './about'

function App() {

  return (
    <div className="App">
      <Router>
        <Link to="/home">Jump to Home page</Link>
        <Link to="/about">Jump to About page</Link>

        <Route path="/home" component={Home}/>
        <Route path="/about" component={About}/>                           

      </Router>
    </div>
  );
}

export default App;
Copy the code

The Home component also wants to set the matching path of the two routing components, namely /home/one and /home/two. At this time, it can be seen that /home/one and /home/two are the second-level nested path of the upper-level route/Home. The code is as follows:

import React from 'react'
import {
    Route,
    Link,
} from 'react-router-dom'
import One from './one'
import Two from './two'

function Home () {
    
    return (
        <>I'm the Home page<Link to="/home/one">The Home/ One page is displayed</Link>
            <Link to="/home/two">Go to the Home/two page</Link>

            <Route path="/home/one" component={One}/>
            <Route path="/home/two" component={Two}/>
        </>)}export default Home
Copy the code

Note: the secondary routing path match of the routing component One in the Home component must be written to /home/one, not/One. Do not think that just because the One component looks like it is inside the Home component, it can be shortened to/One

Dynamic link

NavLink can append an active class name to a link that is currently in the active state, for example:

import { 
    BrowserRouter as Router, 
    Route, 
    NavLink 
} from 'react-router-dom'
import Home from './home'
import About from './about'

function App() {
  return (
    <div className="App">
      <Router>
        <NavLink to="/home" className="link">Jump to Home page</NavLink>
        <NavLink to="/about" className="link">Jump to About page</NavLink>
        <Route path="/home" component={Home}/>
        <Route path="/about" component={About}/>
      </Router>
    </div>
  );
}

export default App;
/* Styles the active class */
.active {
    font-weight: blod;
    color: red;
}
Copy the code

The effect is as follows:

Route Matching optimization

When the jump link is clicked, it will automatically try to match the corresponding paths of all routes, as shown in the figure:

Normally, only one rule needs to be matched and rendered. That is, after a successful match, no subsequent matching attempt is required. In this case, Switch component can be used, as shown below:

import { 
  BrowserRouter as Router, 
  Route, 
  NavLink,
  Switch,
} from 'react-router-dom'
import Home from './home'
import About from './about'

function App() {
  return (
    <div className="App">
      <Router>
        <NavLink to="/home" className="link">Jump to Home page</NavLink>   
        <NavLink to="/about" className="link">Jump to About page</NavLink>

        <Switch>
          <Route path="/home" component={Home}/>       
          <Route path="/about" component={About}/>      
          <Route path="/home" component={Home}/>       
          <Route path="/home" component={Home}/>{/* Omit ten thousand Route components */}<Route path="/home" component={Home}/>                           
        </Switch>

      </Router>
    </div>
  );
}

export default App;
Copy the code

The effect is as follows:

Summary of main points:

  1. multipleRouteComponents are placed in one at a timeSwitchComponent to avoid multiple meaningless route matches and improve performance

redirect

If the Redirect link does not match any of the Route components, a 404 page will be displayed, so we need a Redirect component that looks like this:

import { 
  BrowserRouter as Router, 
  Route, 
  NavLink,
  Switch,
  Redirect,
} from 'react-router-dom'
import Home from './home'
import About from './about'

function App() {
  return (
    <div className="App">
      <Router>
        <NavLink to="/home" className="link">Jump to Home page</NavLink>   
        <NavLink to="/about" className="link">Jump to About page</NavLink>
        <NavLink to="/shop" className="link">Jump to Shop page</NavLink>{/* Click to jump to /shop, but the path is not set */}<Switch>
          <Route path="/home" component={Home}/>       
          <Route path="/about" component={About}/>      
          <Redirect to="/home" />{/* Redirect to /home */}</Switch>

      </Router>
    </div>
  );
}

export default App;
Copy the code

The effect is as follows:

Routing and the cords

All parameters passed by the route are obtained in the props of the forward route component. Each parameter is received in a slightly different way

There are three modes of route parameter transmission

The first kind of

The first is to carry parameters on the jump path of the Link component and receive parameters on the matching path of the Route component by: parameter name, code as follows:

import { 
  BrowserRouter as Router, 
  Route, 
  NavLink,
  Switch,
} from 'react-router-dom'
import Home from './home'
import About from './about'

function App() {
  return (
    <div className="App">
      <Router>{/* the path to /home contains two arguments */<NavLink to="/ home/Joe / 18" className="link">Jump to Home page</NavLink>   
        <NavLink to="/about" className="link">Jump to About page</NavLink>

        <Switch>{/* Received name and age at the same position on /home matching path */}<Route path="/home/:name/:age" component={Home}/>       
          <Route path="/about" component={About}/>                           
        </Switch>

      </Router>
    </div>
  );
}

export default App;
Copy the code

Try jumping and print the props for the routing component

As you can see, the arguments to the first method are obtained via functions.mate.params

The second,

The second way is by following the Link after the jump Link of the Link component. At the beginning, like? A =1&b=3

import { 
  BrowserRouter as Router, 
  Route, 
  NavLink,
  Switch,
} from 'react-router-dom'
import Home from './home'
import About from './about'

function App() {
  return (
    <div className="App">
      <Router>{/* The jump path is followed by? Name = age=18 */}<NavLink to="/home? Name = zhang SAN & age = 18" className="link">Jump to Home page</NavLink>   
        <NavLink to="/about" className="link">Jump to About page</NavLink>

        <Switch>{/* No need to receive */}<Route path="/home" component={Home}/>       
          <Route path="/about" component={About}/>                           
        </Switch>

      </Router>
    </div>
  );
}

export default App;
Copy the code

Try jumping and print the props for the routing component

As you can see, the parameter of the second method is obtained through props. Location. search, but the parameter of the second method needs to be converted by itself

The third kind of

The third way is to write the Link component’s to jump property as an object and pass the parameter through the state property as follows:

import { 
  BrowserRouter as Router, 
  Route, 
  NavLink,
  Switch,
} from 'react-router-dom'
import Home from './home'
import About from './about'

function App() {
  return (
    <div className="App">
      <Router>{/* Describe the to attribute as an object, with the path attribute named pathName and the parameter attribute named state */}<NavLink to={{pathname: "/home", state: {name:Zhang SAN,age: 18}}} className="link">Jump to Home page</NavLink>   
        <NavLink to="/about" className="link">Jump to About page</NavLink>

        <Switch>{/* There is no need to specifically accept attributes */}<Route path="/home" component={Home}/>       
          <Route path="/about" component={About}/>                           
        </Switch>

      </Router>
    </div>
  );
}

export default App;
Copy the code

Try jumping and print the props for the routing component

As you can see, the parameter to the third method is obtained from props. Location. state

Functional routing

The react-router-DOM Link component is used to redirect to and from a routing component

But sometimes, we need a more flexible way to jump route, for example, by calling a function to jump route anytime and anywhere, this is called functional routing

Functional routing uses the following five methods (the screenshot below is from the props of the routing component)

The five methods are push, replace, goForward, goBack and Go. Next, I will introduce these methods in order

push

The push method is to redirect the page to the corresponding path and leave a record in the browser (i.e. go back to the previous page via the browser’s back button)

For example, set a button in the routing component Home that calls the push method to jump to the/About page

import React from 'react'

function Home (props) {

    let pushLink = () = > {
        props.history.push('/about')}return (
        <div className="a">I'm the Home page<button onClick={pushLink}>Jump to the About page</button>
        </div>)}export default Home
Copy the code

The jump effect is as follows:

As you can see, after jumping through the push method, you can go back to the previous page through the browser’s back button

replace

The replace method is similar to the push method, except that the previous page is not saved in the browser after the jump (that is, the browser cannot go back to the previous page).

Let’s change the code

import React from 'react'

function Home (props) {

    let replaceLink = () = > {
        props.history.replace('/about')}return (
        <div className="a">I'm the Home page<button onClick={replaceLink}>Jump to the About page</button>
        </div>)}export default Home
Copy the code

The jump effect is as follows:

As you can see, the initial path is ‘/’, then jump to ‘/home’, then click the button to go to the /about page using the replace method. Finally, the browser’s back button returns to the/page, indicating that the /home in the middle is not stored in the browser’s record

goForward

Calling the goForward method is equivalent to clicking the browser’s back to the next page button, as shown below:

I’m not going to show you too much here

goBack

Calling the goBack method is equivalent to clicking the browser’s back to previous page button, as shown below:

go

The go method, as its name implies, is used to jump to a specified path.

The method takes a single argument (of type Number) as follows:

  1. When the parameter is positiven“, it indicates the next stepnA page. For example,go(1)That’s like calling it oncegoForwardmethods
  2. When the parameter is negativen“, it indicates the jump tonA page. For example,go(-3)That’s the equivalent of three callsgoBackmethods
  3. When the parameter is0“, refresh the current page

Common components use routing

Two concepts are distinguished here, common component and routing component

The components rendered by the Route component are routed components, and the rest are basically normal components

For example, in the following code: the Home component is a routing component; App components are common components

import {
  BrowserRouter as Router, 
  Route, 
  NavLink,
  Switch,
} from 'react-router-dom'
import Home from './home'

export default function App() {
  
  return (
    <div className="App">
      <Router>
        <NavLink to='/home' className="link">Jump to Home page</NavLink>   

        <Switch>
          <Route path="/home" component={Home}/>                              
        </Switch>

      </Router>
    </div>
  );
}
Copy the code

However, the biggest difference between a routed component and a normal component is whether the component props property has something like this:

At this point, react-router-dom provides a withRouter method that enables ordinary components to have those methods or data available as routing components

The usage method is as follows:

import { 
  BrowserRouter as Router, 
  Route, 
  NavLink,
  Switch,
  withRouter,  // 1. Import witRouter
} from 'react-router-dom'
import About from './about'

function App(props) {

  console.log(props);   // 3. Print props for the common component App. The props for the common component can have functions similar to those of the routing component

  return (
    <div className="App">
      <Router>
        <NavLink to="/about" className="link">Jump to About page</NavLink>

        <Switch>
          <Route path="/about" component={About}/>                           
        </Switch>

      </Router>
    </div>
  );
}

export default withRouter(App);  // 2. Use the withRouter method to wrap the common components
Copy the code

supplement

replace

In the functional route, there are two main jump types, push and replace, so in the non-functional route, you can also define the jump type, the specific implementation code is as follows:

import { 
    BrowserRouter as Router, 
    Route, 
    Link 
} from 'react-router-dom'
import Home from './home'
import About from './about'

function App() {
  return (
    <div className="App">
      <Router>
        <Link to="/home" className="link">Jump to Home page</Link>
        <Link to="/about" className="link">Jump to About page</Link>

        <Route path="/home" component={Home} replace={true}/>{/* replace is true and the jump type is replace */}<Route path="/about" component={About} replace={false}/>{/* replace is false, jump type is push */}</Router>
    </div>
  );
}

export default App;
Route'component has a'replaceThe 'property can be set to jump type, when is'true', the jump type is'replace`; For `false', the jump type is'push
Copy the code

excat

Routing matches are fuzzy by default, for example:

import { 
  BrowserRouter as Router, 
  Route, 
  Link,
} from 'react-router-dom'
import Home from './home'
import About from './about'

function App() {

  return (
    <div className="App">
      <Router>
        <Link to="/home/abc">Jump to Home page</Link>{/* jump to /home/abc, but there is no ABC in the actual home */ /}<Link to="/about/abc">Jump to About page</Link>{/* jump to /about/ ABC, but there is no ABC under home */ /}<Route path="/home" component={Home} />{/* Route matching rule is /home. Exact attribute is not set.<Route path="/about" component={About} exact/>{/* Route matching rule is set to /about and exact attribute is set.</Router>
    </div>
  );
}

export default App;
Copy the code

The effect is as follows:

The first Route component matches /home first, so the home component is rendered. For /about/ ABC, the second Route component matches exactly, i.e. /about/ ABC is not equal to /about, so the About component is not rendered

Conclusion:

  1. If you want an accurate match, all you need is aRouteThe component’sexactProperty set totrueCan be
  2. Precision matching should be used with caution because it may affect the use of nested routines