No-nonsense quick start React routing development

No-nonsense quick start React routing development

Install

Enter the following command to install it:

// npm
npm install react-router-dom

//yarn
yarn add react-router-dom

react-router related tags

There are eight commonly used components of react-router :

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

Simple route jump

Implement a simple first-level routing 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;

The effect is as follows:

picture

Summary of key points:

  • Route component must be inside Router component
  • The value of to attribute of Link component is the path to jump to after clicking
  • path attribute of Route component matches to attribute of Link tag; component attribute represents the component object rendered after Route component successfully matches.

Nested route jump

React 's routing matching level is in order

For example, in the App component, two matching paths of the routing components are set, namely /home and /about . The 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">Go to Home page</Link>
        <Link to="/about">Go to About page</Link>

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

      </Router>
    </div>
  );
}

export default App;

Then, in the Home component, we also want to set the matching paths of two routing components, namely /home/one and /home/two . At this point, we can see that /home/one and /home/two are the second-level nested routes 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 am the Home page <Link to="/home/one">Jump to Home/one page</Link>
            <Link to="/home/two">Go to Home/two page</Link>

            <Route path="/home/one" component={One}/>
            <Route path="/home/two" component={Two}/>
        </>
    )
}

export default Home

Special note: The secondary route path matching of the routing component One in the Home component must be written as /home/one , not /one . Don't think that One component can be abbreviated as /one just because it seems to be in the Home component.

Dynamic Linking

NavLink can attach an active class name to the link that is currently in 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;
/* Set the style of the active class */
.active {
    font-weight: black;
    color: red;
}

The effect is as follows:

picture

Route matching optimization

When you click on the redirect link, it will automatically try to match all the paths corresponding to Route , as shown in the figure:

picture

Under normal circumstances, you only need to match one rule and render it. That is, after a successful match, there is no need to make subsequent matching attempts. In this case, you can use Switch component, 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}/>        
          {/* Ten thousand Route components are omitted here*/}                  
          <Route path="/home" component={Home}/>                           
        </Switch>

      </Router>
    </div>
  );
}

export default App;

The effect is as follows:

picture

Summary of key points:

Placing multiple Route components in a Switch component can avoid multiple meaningless route matches and improve performance.

Redirect

When the page jumps, if the jump link does not match any Route component, the 404 page will be displayed, so we need a redirect component Redirect , the code is as follows:

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" /> {/* When all the above Route components fail to match, redirect to /home */}                    
        </Switch>

      </Router>
    </div>
  );
}

export default App;

The effect is as follows:

picture

Routing parameters

All parameters passed by the route will be obtained in props of the jump route component. Each parameter passing method receives the parameters in a slightly different way.

There are three ways to pass parameters through routing. Let's take a look at them one by one.

The first

The first is to carry parameters on the jump path of Link component and receive parameters through the parameter name on the matching path of Route component :參數名The code is 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 /home carries two parameters, Zhang San and 18*/}
        <NavLink to="/home/张三/18" className="link">Jump to Home page</NavLink>   
        <NavLink to="/about" className="link">Jump to About page</NavLink>

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

      </Router>
    </div>
  );
}

export default App;

Try to jump and print props of the routing component

picture

As you can see, the parameters of the first method are obtained through props.match.params

The second

The second way is to pass parameters starting with ? after the jump link of Link component, such as ?a=1&b=3 The code is 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>
        {/* Pass two parameters starting with ? after the jump path, namely name=张三, age=18 */}
        <NavLink to="/home?name=张三&age=18" className="link">Jump to Home page</NavLink>   
        <NavLink to="/about" className="link">Jump to About page</NavLink>

        <Switch>
          {/* No need to do receiving operation here*/}
          <Route path="/home" component={Home}/>       
          <Route path="/about" component={About}/>                           
        </Switch>

      </Router>
    </div>
  );
}

export default App;

Try to jump and print props of the routing component

picture

As you can see, the parameters of the second method are obtained through props.location.search , but the parameters here need to be further converted by yourself, so I won’t explain it in detail here.

The third

The third way is to write the to jump property of Link component in the form of an object and pass the parameters through state property. The code is 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 in the form of an object, the path attribute is named pathname, and the parameter attribute is named state */}
        <NavLink to={{pathname: "/home", state: {name: '张三', age: 18}}} className="link">Jump to Home page</NavLink>   
        <NavLink to="/about" className="link">Jump to About page</NavLink>

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

      </Router>
    </div>
  );
}

export default App;

Try to jump and print props of the routing component

picture

As you can see, the parameters of the third method are obtained through props.location.state

Functional Routing

The above mainly jumps to a certain routing component through Link component in react-router-dom

But sometimes, we need a more flexible way to jump routes, such as calling a function to jump routes anytime and anywhere. This is called functional routing.

There are 5 methods used in functional routing (the screenshot below is from props of the routing component)

insert image description here

5 methods are push , replace , goForward , goBack , and go . Next, we will introduce these methods in order.

push

The push method is to jump the page to the corresponding path and leave a record in the browser (that is, you can return to the previous page through the browser's back button)

For example, set a button in the routing component Home , click it and call 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 am on the Home page <button onClick={pushLink}> Jump to the about page </button>
        </div>
    )
}

export default Home

The jump effect is as follows:

picture

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

replace

replace method is similar to the push method, except that the previous page record will not be saved in the browser after the jump (that is, you cannot return to the previous page through the browser's back button)

Change the code

import React from 'react'

function Home (props) {

    let replaceLink = () => {
        props.history.replace('/about')
    }
    
    return (
        <div className="a">
            I am on the Home page <button onClick={replaceLink}> Jump to the about page </button>
        </div>
    )
}

export default Home

The jump effect is as follows:

picture

As you can see, the initial path is '/', then jumps to '/home', and then clicks the button to jump to the /about page through the replace method. Finally, I returned to the / page through the browser's back button, indicating that /home in the middle was not stored in the browser's record.

goForward

Calling the goForward method is equivalent to clicking the browser's return to the next page button, as shown in the following figure:

picture

I won’t do more demonstrations here.

goBack

Calling the goBack method is equivalent to clicking the browser's button to return to the previous page, as shown in the following figure:

insert image description here

go

As the name suggests, the go method is used to jump to the specified path.

This method accepts one parameter (parameter type is Number ), as follows:

  • When the parameter is a positive number n , it means jumping to the next n pages. For example, go(1) is equivalent to calling the goForward method once.
  • When the parameter is a negative number n , it means jumping to the previous n pages. For example, go(-3) is equivalent to calling goBack method three times.
  • When the parameter is 0 , it means refreshing the current page

Common components use routing

There are two concepts here: ordinary components and routing components

Components rendered by Route component are routing components, and the rest are basically ordinary components

For example, in the following code: Home component is a routing component; App component is a normal component

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>
  );
}

Then, the biggest difference between routing components and ordinary components is whether props attribute of the component has the content shown in the following figure: (the former has, the latter does not)

picture

At this point, react-router-dom provides a withRouter method, which allows ordinary components to have the same methods or data as routing components.

Here’s how to use it:

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

function App(props) {

  console.log(props); // 3. Try to print the props of the normal component App, and find that there is already content in the props, that is, the normal component can also have the same function as 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 ordinary components

Replenish

replace

There are two main types of jumps in functional routing, push and replace . In non-functional routing, you can also customize 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, jump type is replace */}
        <Route path="/about" component={About} replace={false}/> {/* replace is false, jump type is push */}
      </Router>
    </div>
  );
}

export default App;
The Route component has a replace attribute that can set the redirect type. When the value is true, the redirect type is replace; when it is false, the redirect type is push.

excat

The default route matching is fuzzy matching. 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 routing component under home*/}
        <Link to="/about/abc">Jump to About page</Link> {/* Jump to /about/abc, but there is no abc routing component under home*/}

        <Route path="/home" component={Home} /> {/* The route matching rule is /home, the exact attribute is not set, and the current match is fuzzy*/}
        <Route path="/about" component={About} exact/> {/* The route matching rule is /about, the exact attribute is set, and the current match is exact*/}

      </Router>
    </div>
  );
}

export default App;

The effect is as follows:

picture

As can be seen in the figure, when jumping to /home/abc , the first Route component is fuzzy matching, so it matches /home first, so Home component is rendered; when jumping to /about/abc , the second Route component is an exact match, that is, /about/abc is not equal to /about , so the About component is not rendered either.

Summarize:

  • If you want an exact match, just set exact property of Route component to true .
  • Exact matching should be used with caution, as it may affect the use of nested routes.

The above is the detailed content of the no-nonsense quick start with React routing. For more information about React routing quick start, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • How to implement React routing authentication
  • Several implementation solutions for lazy loading of React routes
  • Implementation of React-router4 route monitoring
  • Detailed explanation of the redirection methods of each version of React routing
  • React's method of controlling login verification from react-router routing
  • React-router v4: How to use history to control route jumps
  • Solution to the 404 issue when directly entering the routing path after configuring the React project URL in Nginx
  • Summary of React-router v4 routing configuration method

<<:  Detailed explanation of SSH password-free login configuration under Linux

>>:  MySQL 5.7.20 installation and configuration method graphic tutorial under Windows

Recommend

Implementation of interactive data between QT and javascript

1. Data flows from QT to JS 1. QT calls the JS fu...

Mysql keeps the existing content and adds content later

This command modifies the data table ff_vod and a...

uniapp dynamic modification of element node style detailed explanation

Table of contents 1. Modify by binding the style ...

Is it true that the simpler the web design style, the better?

Original address: http://www.webdesignfromscratch...

Detailed explanation of VUE responsiveness principle

Table of contents 1. Responsive principle foundat...

jquery+springboot realizes file upload function

This article example shares the specific code of ...

How to point the target link of a tag to iframe

Copy code The code is as follows: <iframe id=&...

Completely uninstall MySQL database in Windows system to reinstall MySQL

1. In the control panel, uninstall all components...

Writing a web calculator using javascript

This article mainly records the effect of using j...

Description of the execution mechanisms of static pages and dynamic pages

1. A static page means that there are only HTML ta...

Vue implements irregular screenshots

Table of contents Image capture through svg CSS p...

Detailed explanation of how to solve the problem of too long content in CSS

When we write CSS, we sometimes forget about the ...

Install docker offline by downloading rpm and related dependencies using yum

You can use yum to install all dependencies toget...