ReactRouterDom-v5&v6 usage and similarities and differences

The author of this article is a front-end development engineer of 360 Qiwu Troupe

Introduction:

React Router Dom is a common library used to implement routing functions in React.js. In React applications, routing can help us manage navigation and state between pages, and implement dynamic loading of components. This article will dive into the two major versions of React Router Dom: V5 and V6, and describe their usage, similarities and differences.

v5 usage

The V5 release of React Router Dom is built on top of React Router. It is a stable and widely used release that provides powerful routing features for React applications. The following is a usage example of the V5 version:

Install React Router DOM:

npm install react-router-dom@5
yarn add react-router-dom@5

Import required components:

import { BrowserRouter as Router, Route, Link } from 'react-router-dom';

Define the route in the application:

<Router>
  <nav>
    <ul>
      <li>
        <Link to="/">首页</Link>
      </li>
      <li>
        <Link to="/about">关于</Link>
      </li>
    </ul>
  </nav>

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

Use route parameters in components:

import { useParams } from 'react-router-dom';

function User() {
  let { id } = useParams();
  return <h2>用户ID: {id}</h2>;
}
  • The V5 version of React Router Dom provides many powerful features, such as nested routing, routing parameters, redirection, etc. But in V6 version, their usage may be different.

v6 usage

The V6 release of React Router Dom is a brand new rewrite aimed at providing a cleaner and more intuitive API. The following is a usage example for the V6 version:

Install React Router Dom V6:

npm install react-router-dom@next
yarn add react-router-dom@next

Import required components:

import { BrowserRouter as Router, Route, Link, Routes, Outlet } from 'react-router-dom';

Define the route in the application:

<Router>
  <nav>
    <ul>
      <li>
        <Link to="/">首页</Link>
      </li>
      <li>
        <Link to="/about">关于</Link>
      </li>
    </ul>
  </nav>

  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/about" element={<About />} />
  </Routes>
</Router>

Use route parameters in components:

import { useParams } from 'react-router-dom';

function User() {
  let { id } = useParams();
  return <h2>用户ID: {id}</h2>;
}
  • The V6 version of React Router Dom introduces some new concepts like Routes and Outlets . Routes are used to define routing collections, while Outlet is used in parent routing components

BrowserRouter and HashRouter

BrowserRouter and HashRouter are two commonly used router components in React Router Dom, which are used to handle routing in React applications.

BrowserRouter:

BrowserRouter uses HTML5's History API to implement routing functions. It uses history.pushState()and history.replaceState()methods to modify the browser's URL without causing a page reload. BrowserRouter uses browser-based URL paths to match and render corresponding components. When using BrowserRouter, all routing rules need to be placed on the server-side routing configuration to ensure that the corresponding components can be loaded correctly when refreshing or directly accessing a certain URL.

HashRouter:

HashRouter uses the hash part (#) of the URL to implement the routing function. It adds a hash router to the URL and responds to URL changes by listening to the window object's hashchange event. When the hash part of the URL changes, HashRouter will match the corresponding routing rules and render the corresponding components. Compared with BrowserRouter, HashRouter has wider compatibility, because changes in the hash part will not trigger the browser to initiate a request to the server, but will be processed on the client side. This is very useful for some applications that need to be deployed on static servers.

import { BrowserRouter as Router, Route } from 'react-router-dom';
import { HashRouter as Router, Route } from 'react-router-dom';

function App() {
  return (
    <Router>
      <Route path="/" component={Home} />
      <Route path="/about" component={About} />
    </Router>
  );
}
  • It should be noted that when using HashRouter, the hash part of the URL will be added after the root path of the application, for example: http://example.com/#/about . This approach allows the application to correctly respond to URL changes and display the corresponding components.

  • Summary: BrowserRouter and HashRouter are two commonly used router components in React Router Dom. BrowserRouter uses HTML5's History API to implement the routing function, while HashRouter uses the hash part of the URL to implement the routing function. The choice of which router to use depends on the deployment environment and compatibility requirements of the application. If the application is deployed on a server that supports HTML5 History API, BrowserRouter can be used; if wider compatibility is required, or the application is a purely static website, HashRouter can be used.

Important configuration in Router

BrowserRouter and homepage

In the package.json file of a React application, the base URL path of the application can be specified by setting the "homepage" parameter. This base URL path affects the route matching rules used in React Router and the generation of navigation links. When the "homepage" parameter is set, React Router's route matching rules and navigation links will take this base URL path into account. They are automatically prefixed with the base URL path to ensure correct matching of routes and generation of navigation links. For example, assuming the "homepage" parameter is set to "/my-app", here are some examples when using React Router:

BrowserRouter:

import { BrowserRouter as Router, Route } from 'react-router-dom';

function App() {
  return (
    <Router>
      <Route path="/" component={Home} /> {/* 匹配的路径为:/my-app/ */}
      <Route path="/about" component={About} /> {/* 匹配的路径为:/my-app/about */}
    </Router>
  );
}

In BrowserRouter, after the "homepage" parameter is set, the path in the route matching rule will automatically add the base URL path as a prefix.

Link component:

import { Link } from 'react-router-dom';

function Navigation() {
  return (
    <nav>
      <ul>
        <li>
          <Link to="/">首页</Link> {/* 生成的链接为:/my-app/ */}
        </li>
        <li>
          <Link to="/about">关于</Link> {/* 生成的链接为:/my-app/about */}
        </li>
      </ul>
    </nav>
  );
}
  • In the Link component, after setting the "homepage" parameter, the generated navigation link will automatically add the base URL path as a prefix.

  • Summary: Setting the "homepage" parameter in package.json can specify the base URL path of the React application. This base URL path affects the generation of route matching rules and navigation links in React Router, making sure they take into account the base URL path as a prefix. This is very useful when deploying React applications to different paths, ensuring that routes are correctly matched and navigation links are generated.

HashRouter and homepage

In React Router, HashRouter is not affected by the "homepage" parameter in package.json. Setting the "homepage" parameter only affects the behavior of the BrowserRouter, not the HashRouter directly. HashRouter uses the hash part (#) of the URL to implement routing functions, independent of the base URL path. Whether or not the "homepage" parameter is set, HashRouter always uses the hash part relative to the root directory to match routing rules and generate navigation links. For example, assuming the "homepage" parameter is set to "/my-app", the following is an example when using HashRouter:

import { HashRouter as Router, Route } from 'react-router-dom';

function App() {
  return (
    <Router>
      <Route path="/" component={Home} /> {/* 匹配的路径为:/#/ */}
      <Route path="/about" component={About} /> {/* 匹配的路径为:/#/about */}
    </Router>
  );
}

In HashRouter, no matter what the "homepage" parameter is set to, the matching rules of the route and the generated navigation links will still use /#/such /#/abouta hash part of the path.

  • Summary: HashRouter is not affected by the "homepage" parameter in package.json. Whether or not the "homepage" parameter is set, HashRouter always uses the hash part relative to the root directory to match routing rules and generate navigation links. The "homepage" parameter only affects the behavior of the BrowserRouter.

Other parameters

  1. basename : The basename parameter can be used by setting the basename property in the Router component as follows:

import { BrowserRouter as Router, Route } from 'react-router-dom';

function App() {
  return (
    <Router basename="/my-app">
      <Route path="/" component={Home} />
      <Route path="/about" component={About} />
    </Router>
  );
}
  1. path : Use the path attribute in the Route component to define the path of the routing rule, as follows:

import { BrowserRouter as Router, Route } from 'react-router-dom';

function App() {
  return (
    <Router>
      <Route path="/" exact component={Home} />
      <Route path="/about" component={About} />
    </Router>
  );
}
  1. exact : By setting the exact property to true, it is ensured that the URL path is rendered only when it exactly matches the path parameter, as shown below:

import { BrowserRouter as Router, Route } from 'react-router-dom';

function App() {
  return (
    <Router>
      <Route exact path="/" component={Home} />
      <Route exact path="/about" component={About} />
    </Router>
  );
}
  1. strict : Set the strict attribute to true to match on URL paths with a slash at the end, as follows:

import { BrowserRouter as Router, Route } from 'react-router-dom';

function App() {
  return (
    <Router>
      <Route strict path="/" component={Home} />
      <Route strict path="/about/" component={About} />
    </Router>
  );
}

The above examples show how to use these parameters to affect path generation and matching. According to specific needs, these parameters can be set in the corresponding components to achieve the desired routing configuration.

quote

  • https://reactrouter.com/en/main/router-components/browser-router

  • https://www.npmjs.com/package/react-router-dom

- END -

About Qi Wu Troupe

Qi Wu Troupe is the largest front-end team of 360 Group, and participates in the work of W3C and ECMA members (TC39) on behalf of the group. Qi Wu Troupe attaches great importance to talent training, and has various development directions such as engineers, lecturers, translators, business interface people, and team leaders for employees to choose from, and provides corresponding technical, professional, general, and leadership training course. Qi Dance Troupe welcomes all kinds of outstanding talents to pay attention to and join Qi Dance Troupe with an open and talent-seeking attitude.

e934f70bb62755e0b0a6565a65097a13.png

Guess you like

Origin blog.csdn.net/qiwoo_weekly/article/details/130878036