What is front-end routing?

Traditionally, routing is a back-end concept. However, when the URL changes, the backend returns the corresponding file according to the change.

With the advent of single-page applications, the front end also needs to handle routing:

  • We don’t want the URL change to cause the browser to refresh, just switch the page content.
  • When you visit the page again, you can display the corresponding content based on the URL
  • More semantic organizational resources

React Router allows you to quickly add views and data streams to your applications. The React Router is a Redux Router that allows you to add views and data streams to your applications. It also keeps pages and urls in sync.

React Router

The routing infrastructure is very simple, mainly divided into three parts: [route definition], [Router], [page]. We map the relationship between PATH and component through [route definition], and then after [Router] parsing, display the corresponding content of Path on the component container of [page].

The React the Router features

  • Express uses a routing table to configure routes. React Router uses a React Tag to define routes, which can be written anywhere.

    const App = () = > {
      return (
        <div>
          <Router>
            <nav>
              <Link to="/about">About</Link>
            </nav>
            <div>
              <Route path="/about" component={About}></Route>
            </div>
          </Router>
        </div>
      );
    };
    Copy the code
  • Dynamic Routing corresponds to Static Routing. The Routing table of Static Routing is unchanged. When the project starts to run, we know all the Routing relations:

    var express = require("express");
    var router = express.Router();
    
    router.get("/".function (req, res) {
      res.send("Wiki home page");
    });
    
    router.get("/about".function (req, res) {
      res.send("About this wiki");
    });
    
    module.exports = router;
    Copy the code

    The React Router is only parsed when the page is render.

    as a component, when not rendered, is not accessible to its Route (/about); Therefore, the routing table increases as the component is rendered.

    <Route path="/about" component={About} />
    Copy the code

Three ways to implement routes

The React Router provides three ways to implement routes:

  • URL routing takes advantage of the new pushState() and replaceState() methods in THE HTML5 History Interface. When they change the current URL, the browser does not immediately send a request to the back end. URL routing (/home, /about) can be used as long as the browser supports it

    import { BrowserRouter } from "react-router-dom";
    Copy the code
    <BrowserRouter
      basename={optionalString}
      forceRefresh={optionalBool}
      getUserConfirmation={optionalFunc}
      keyLength={optionalNumber}
    >
      <App />
    </BrowserRouter>
    Copy the code
  • Hash routes are the # symbol in the URL of the address bar (this hash is not a cryptographic hash) – http://www.abc.com/#/hello. The hash, while present in the URL, is not included in the HTTP request and has no impact on the back end, so changing the hash does not reload the page.

    import { HashRouter } from "react-router-dom";
    Copy the code
    <HashRouter
      basename={optionalString}
      getUserConfirmation={optionalFunc}
      hashType={optionalString}
    >
      <App />
    </HashRouter>
    Copy the code
  • In-memory Routing The history of routes is stored in memory and not reflected in the browser address bar, which is useful in testing and non-browser environments such as React Native.

    import { MemoryRouter } from "react-router";
    Copy the code
    <MemoryRouter
      initialEntries={optionalArray}
      initialIndex={optionalNumber}
      getUserConfirmation={optionalFunc}
      keyLength={optionalNumber}
    >
      <App />
    </MemoryRouter>
    Copy the code

The installation

  • npm
npm install react-router-dom --save
Copy the code
  • yarn
yarn add react-router-dom --dev
Copy the code

1st Example: Basic route switchover

import React from "react";
import { BrowserRouter as Router, Route, Switch, Link } from "react-router-dom";

const App = () = >({/ * the Router ⬇ ️ * /}
  <Router>
    {/* Route switchover ⬇️ */}
    <nav>
      <ul>
        <li>
          <Link to="/home">home</Link>
        </li>
        <li>
          <Link to="/about">about</Link>
        </li>
        <li>
          <Link to="/users">users</Link>
        </li>
      </ul>
    </nav>
    {/* Container components ⬇️ */}
    <Switch>
      {/* Route matching list ⬇️ */}
      <Route path="/home" component={Home}></Route>
      <Route path="/about" component={About}></Route>
      <Route path="/users" component={Users}></Route>
    </Switch>
  </Router>
);

function Home() {
  return <div>Home</div>;
}
function About() {
  return <div>About</div>;
}
function Users() {
  return <div>Users</div>;
}

export default App;
Copy the code

Organize resources based on routing

  • Loose coupling of business logic

    We integrate business-related/code-related parts through routing.

  • Easy to extend, refactor, and maintain

    Because the implementation of routes is not mixed into business code, but abstracted with React Router, the logical units of services become one page after another. Whether expanding new pages or reconstructing and maintaining new pages, it is more clear from the perspective of routes.

  • The routing layer implements Lazy Load

    Because the routes are defined in a uniform place, it is more convenient to perform Lazy Load from the route level, and different components can be loaded. The efficiency of the first loading is very high.

Core API Introduction

<Route>

The

component is the most important component of the React Router. Its basic function is to display the corresponding component when the path matches.

<Router>
  {
    // exact: Specifies whether the exact path is matched
  }
  <Route exact path="/" component={Home}></Route>
  <Route path="/about" component={About}></Route>
</Router>
Copy the code

Also,

is non-exclusive, meaning it can render two matching components at the same time (multiple matching) :

<Router>
  <Route path="/:user">
    <User />
  </Route>
  <Route>
    <NoMatch />
  </Route>
</Router>

// Match to path /user,
// Component UserInfo and component UserDetail are presented simultaneously.
Copy the code

Props

  • Path: indicates the path in the URL.

  • Component: Individual components are rendered when a URL is matched. It can be retrieved by the parent route component’s this.props. Children.

    const routes = (
      <Route component={App}>
        <Route path="groups" component={Groups} />
        <Route path="users" component={Users} />
      </Route>
    );
    
    class App extends React.Component {
      render() {
        return(< div > {/ * this is < the Users > or < Groups > * /} {this. Props. Children} < / div >). }}Copy the code
  • Components: Defines one or more named components, as {name: Component}, which can be retrieved by the parent route component’s this.props[name].

    const routes = (
      <Route component={App}>
        <Route
          path="groups"
          components={{ main: Groups.sidebar: GroupsSidebar}} / >
        <Route path="users" components={{ main: Users.sidebar: UsersSidebar}} >
          <Route path="users/:userId" component={Profile} />
        </Route>
      </Route>
    );
    
    class App extends React.Component {
      render() {
        const { main, sidebar } = this.props;
        return (
          <div>
            <div className="Main">{main}</div>
            <div className="Sidebar">{sidebar}</div>
          </div>); }}Copy the code

<Switch>

Only the first route that matches is displayed (changing the default multi-match behavior).

<Router>
  <Route path="/:user">
    <User />
  </Route>
  <Route>
    <NoMatch />
  </Route>
</Router>

// Match to path /1,
// Only the component User is displayed simultaneously.
Copy the code

<Link>

The React Router takes over the React Router instead of triggering a browser refresh.

<Link to="/about">About</Link>
Copy the code

Props

  • To: indicates the path of the jump link.
  • replace: in order totrueReplaces the current path in history instead of adding it.

<NavLink>

Similar to , but adds the current selected state (className)

<NavLink to="/faq" activeClassName="selected">
  FAQs
</NavLink>
Copy the code

Props

  • ActiveClassName: Class added when the route is activated. Default is active.

  • ActiveStyle: Style added when the route is activated.

    <NavLink
      to="/faq"
      activeStyle={{
        fontWeight: "bold".color: "red",
      }}
    >
      FAQs
    </NavLink>
    Copy the code

<Prompt>

When the user leaves the page, prompt the user whether to leave the current page (such as filling in the form half).

<Prompt when={formIsHalfFilledOut} message="Are you sure you want to leave?" />
Copy the code

Props

  • Message: indicates the message prompting the user
  • when: <Prompt>Render conditions of

<Redirect>

Redirects the current page without changing the old URL. For example, login jump

<Route exact path="/">
  {loggedIn ? <Redirect to="/dashboard" /> : <PublicHomePage />}
</Route>
Copy the code

Props

  • To: indicates the redirected URL
  • Form: URL that needs to be redirected

Application of complex routing scenarios

To learn about complex routing scenarios, continue with React Router (under).