The React Router is a powerful routing library for developing React projects. It allows you to quickly add views and data streams to your application while keeping pages and urls in sync.

A, install,react-route-dom

Implement it in your project

npm i react-router-dom
Copy the code

To install reacr – the router

Two, write the simplest route

In my project, App is my root component, and I write the basic route in App component, which is written according to the actual project, or in a separate Router component.

index.js :

import React from 'react';
import ReactDOM from 'react-dom';
import App from './views/App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.register();Copy the code

App.jsx :

import React from 'react'
import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom'
import Home from './Home/Home'
import Login from './Login/Login'

function App() {
  return (
    <Router>
      <Switch>
        <Route path="/home" component={Home} />
        <Route path="/login" component={Login} />
        <Redirect from="*" to="/home" />
      </Switch>
    </Router>
  )
}

export default App
Copy the code
  • Introduced in app.jsxreact-router-domIn the libraryBrowserRouterSet the alias toRouter, andBrowserRouterAnd then there’s the correspondingHashRouter.BrowserRouterIs our most common history route,HashRouterA hash route is a route preceded by a #.
  • The react – the router – dom in the libraryRoute, two attributespathandcomponentIndicates that the matched route ispathWhen the component is loadedcomponent
  • The react – the router – dom in the librarySwitch.SwitchIndicates that only one route is matched at a timeRouteFuzzy matching from the top down (i.e/homeMaybe match at the same time/home/1and/home/2), addedSwitchOnly the first matched component is loaded
  • The react – the router – dom in the libraryRedirect, indicates the redirected route, and has two valuesfromandto.fromIndicates the matched route.toIt is a redirected route
  • At this point, one of our simplest route implementation is complete, can realize the input/homeloadingHomeComponent, input/loginloadingLoginComponent, and all routes that do not match are redirected to/home

3. Realize route jump and navigation route

Above we implemented the basic routing function, but now we can only type in the browser to jump, we want to have a header navigation in the page, or button click to jump.

Create the Header component:

import React from "react";
import { NavLink } from "react-router-dom";
import './Header.scss'

function Header() {
  return (
    <div>
      <ul>
        <li>
          <NavLink to="/home/user"> User management </NavLink> </li> <li> <NavLink to="/home/article"</NavLink> </li> </ul> </div>) }export default Header;
Copy the code
  • Header componentreact-router-domtheNavLink, is used specifically for navigation link jump tag, corresponding toLink. The usage is similar to only onetoProperty indicates which link to click to jump to.
  • NavLinkandLinkThe difference is,NavLinkAn active style will be added to the matching route. We can customize this style, usually used in the overall header navigation component, etc.LinkNo matching routing style, generally used in button click jump etc.

4. Realize multi-level routing nesting

Above we only implemented level 1 routing, but we also want to have level 2 routing in the Home component. How to implement this?

Home components:

import React from "react";
import { Route, Redirect } from "react-router-dom";
import Header from ".. /.. /components/Header/Header";
import User from ".. /User/User";
import Article from ".. /Article/Article";

function Home() {
  return (
    <div>
      <Header />
      <Route path="/home/user" component={User} />
      <Route path="/home/article" component={Article} />
      <Redirect from="*" to="/home/user" />
    </div>
  );
}

export default Home;
Copy the code
  • inHomeComponent introductionreact-router-domtheRouteandRedirectHere we didn’t reintroduceRouterandSwitchBecause they are inAppComponent, global adaptation.
  • The usage is the same as before, except that we match the pathpatha/homeIndicates the level-2 routing mode/home/user
  • And introduce what we wrote beforeHeaderThe component implements a secondary route jump, and its deeper routes are the same as this one, nested in the child component

Dynamic routing and route parameter transmission

We want to use our dynamic routing to pass parameters in the route jump. It is very simple to define the Route as /home/article/:id followed by: parameter name

Look at an example:

import React from "react";
import { Route } from "react-router-dom";
import Article from ".. /Article/Article";

function Home() {
  return (
    <div>
      <Route path="/home/article/:id" component={Article} />
    </div>
  );
}

export default Home;
Copy the code

The route is then followed by the passed ID value when jumping

<Link to="/home/article/1"> </Link>Copy the code

Receives the ID value from the dynamic route in the Article component

import React from 'react'

function Article(props) {
  console.log(props.match.params.id);
  return(<div> article information </div>)}export default Article
Copy the code

At props. Match.params. id, you can receive the value passed to you

But when we want to pass more and more complex parameters in the route this way is very troublesome, we use another way

Route is defined in the usual way

<Route path="/home/article" component={Article} />
Copy the code

Pass parameters when a Link jumps

<Link to="/home/article? a=1&b=2"> </Link>Copy the code

or

<Link to={{
  pathname: "/home/article",
  search: "? a=1&b=2"}}> Article management </Link>Copy the code

Accept arguments in the Article component

import qs from 'qs'
qs.parse(props.location.search)
Copy the code

Introduce QS module and use qs.parse method to parse parameters

Programmatic navigation

It can be seen that our previous route jumps are all Link and NavLink label jumps. However, in some cases, for example, we will perform some logical judgments before jumping and meet the conditions before jumping, and then we need to use our programmatic navigation.

A component that uses Route will receive three properties: History, location, and match. History is used for programmatic navigation. Location and Match are used for routing information, such as the current pathname and parameters

  • props.history.pushWhen a route is redirected, historical records are generated
props.history.push("/home/article")
Copy the code
  • props.history.replaceWhen a route is redirected to replace the current route, no historical record is generated
props.history.replace("/home/article")
Copy the code
  • props.history.go | props.history.goBackFurther | before routing routing step back

Use the React Router in real projects. If you don’t know how to use the React Router, leave a comment below.