Install the React Router

  1. Website: Reactrouter.com/web/guides/…
  2. Install the router: yarn add react-router-dom
  3. Install TS dependencies: yarn add --dev @types/react-router-dom

The React Router is used in the React project

  1. Introduce Router, Route, Switch, Link, Redirect in app.tsx
import {
  Router,
  Switch,
  Route,
  Link,
  Redirect,
} from 'react-router-dom';

Copy the code
  1. The use of the Router
export default function App() {
  return (
    <Router>
      <Switch>
        <Route exact path="/tags">
          <Tags/>
        </Route>
        <Route exact path="/money">
          <Money/>
        </Route>
        <Redirect exact from="/" to="/money"/>
        <Route path="*">
          <NoMatch/>
        </Route>
      </Switch>
      <ul>
        <li>
          <Link to="/tags">The label</Link>
        </li>
        <li>
          <Link to="/money">Charge to an account</Link>
        </li>
      </ul>
    </Router>
  );
}
Copy the code

Code description:

  • Router: You need to write routing code in the Router tag

  • Link: Similar to the A tag, the value of the to attribute is the address of the route to jump to

  • Switch: Renders the first Route or Redirect that matches the address

  • Route: Its path attribute corresponds to Link’s to attribute, and the content it wraps is the component corresponding to this path

  • Exact: Indicates an exact match

  • Redirect: Similar to Route, from indicates the original address, to indicates the new address, which is used as the default page

  • If you need to style the links you click, replace Link with NavLink and use the activeClassName attribute to style the active and inactive links differently

UseParams: Use the useParams hook to obtain the key/value object of the URL parameter of the current route.

2. UseHistory: You can use useHistory to roll back pages.useHistory().goBack()