preface

In early 2018, the React Router lead developers created a lightweight alternative called Reach Router.

Turns out to be against each other, but didn’t thinkReact RouterDirectly used to merge (really sweet!)

At presentv6This is the last version of the beta, and the following features are expected.

  1. <Switch>rename<Routes>.
  2. <Route>New feature changes.
  3. Nested routines have been made easier.
  4. withuseNavigateInstead ofuseHistory.
  5. A new hookuseRoutesInstead ofreact-router-config.
  6. Size reduction: from20kbto8kb

1. <Switch>rename<Routes>

The top-level component will be renamed. But its functionality remains largely the same (hey, fidgeting).

// v5
<Switch>
    <Route exact path="/"><Home /></Route>
    <Route path="/profile"><Profile /></Route>
</Switch>

// v6
<Routes>
    <Route path="/" element={<Home />} />
    <Route path="profile/*" element={<Profile />} />
</Routes>
Copy the code

2. <Route>New feature changes

component/renderbeelementalternative

In a word, in a nutshell. It just gets better.

import Profile from './Profile';

// v5
<Route path=":userId" component={Profile} />
<Route
  path=":userId"
  render={routeProps => (
    <Profile routeProps={routeProps} animate={true} />
  )}
/>

// v6
<Route path=":userId" element={<Profile />} />
<Route path=":userId" element={<Profile animate={true} />} />
Copy the code

3. Nested routines become easier

The specific changes are as follows:

  • <Route children>Changed to accept child routes.
  • than<Route exact>and<Route strict>Simpler matching rules.
  • <Route path>Path hierarchy is clearer.

3.1 Simplified nested routines are defined

Nested routines in V5 must be very clearly defined and require a lot of string matching logic in these components (see you later, realizing this problem).

Look at the previous processing:

// v5
import {
  BrowserRouter,
  Switch,
  Route,
  Link,
  useRouteMatch
} from 'react-router-dom';

function App() {
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/profile" component={Profile} />
      </Switch>
    </BrowserRouter>
  );
}

function Profile() {
  let { path, url } = useRouteMatch();

  return (
    <div>
      <nav>
        <Link to={`${url}/me`}>My Profile</Link>
      </nav>

      <Switch>
        <Route path={`${path}/me`}>
          <MyProfile />
        </Route>
        <Route path={`${path}/:id`}>
          <OthersProfile />
        </Route>
      </Switch>
    </div>
  );
}
Copy the code

In V6, you can remove string matching logic. Don’t need any useRouteMatch()!

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

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="profile/*" element={<Profile/>} />
      </Routes>
    </BrowserRouter>
  );
}

function Profile() {
  return (
    <div>
      <nav>
        <Link to="me">My Profile</Link>
      </nav>

      <Routes>
        <Route path="me" element={<MyProfile />} />
        <Route path=":id" element={<OthersProfile />} />
      </Routes>
    </div>
  );
}
Copy the code

Of course, there is also a more sour operation, which is to define


in the Route directly, and then use the next new API: Outlet

3.2 newAPI:Outlet

{this.props. Children} {this.props. Children}

function App() { return ( <BrowserRouter> <Routes> <Route path="/" element={<Home />} /> <Route path="profile" element={<Profile />}> <Route path=":id" element={<MyProfile />} /> <Route path="me" element={<OthersProfile />} /> </Route> </Routes> </BrowserRouter> ); } function Profile() {return (<div> <nav> <Link to="me">My Profile</Link> </nav> {/* will directly depend on the different routing parameters defined above, Render <MyProfile /> or <OthersProfile /> */} <Outlet /> </div>)}Copy the code

More than 3.3<Routes />

Previously, we could only use one Routes in the React App. But now we can use multiple routes in the React App, which will help us manage multiple application logic based on different routes.

import React from 'react'; import { Routes, Route } from 'react-router-dom'; function Dashboard() { return ( <div> <p>Look, more routes! </p> <Routes> <Route path="/" element={<DashboardGraphs />} /> <Route path="invoices" element={<InvoiceList />} /> </Routes> </div> ); } function App() { return ( <Routes> <Route path="/" element={<Home />} /> <Route path="dashboard/*" element={<Dashboard  />} /> </Routes> ); }Copy the code

4. UseuseNavigateInstead ofuseHistory

From being clear to being blind…

The React Router team is a bit of a joke…

// v5
import { useHistory } from 'react-router-dom';

function MyButton() {
  let history = useHistory();
  function handleClick() {
    history.push('/home');
  };
  return <button onClick={handleClick}>Submit</button>;
};
Copy the code

Now, history.push() will be replaced with navigation() :

// v6
import { useNavigate } from 'react-router-dom';

function MyButton() {
  let navigate = useNavigate();
  function handleClick() {
    navigate('/home');
  };
  return <button onClick={handleClick}>Submit</button>;
};
Copy the code

The use of history will also be replaced with:

// v5
history.push('/home');
history.replace('/home');

// v6
navigate('/home');
navigate('/home', {replace: true});
Copy the code

5. New hooksuseRoutesInstead ofreact-router-config.

Feels like another wave of forcible hooks, but a little cleaner than before…

function App() { let element = useRoutes([ { path: '/', element: <Home /> }, { path: 'dashboard', element: <Dashboard /> }, { path: 'invoices', element: <Invoices />, children: [ { path: ':id', element: <Invoice /> }, { path: 'sent', element: <SentInvoices />}]}, // redirection {path: 'home', redirectTo: '/'}, // 404 not found {path: '*', element: <NotFound /> } ]); return element; }Copy the code

6. Size reduction: from20kbto8kb

React Router V6 brings us convenience while reducing the size of packages by more than half…

Feel can go to see a wave of source code…

7. Migration and other critical fixes…

The React Router v6 Migration Guide is available here

In fact, the new features listed above are basically all the content of the migration.

The basic starter is the update pack:

$ npm install react-router@6 react-router-dom@6
# or, for a React Native app
$ npm install react-router@6 react-router-native@6
Copy the code

React Router V6 uses a simplified path grid that supports only two placeholders: the dynamic: ID style parameter and the * wildcard

The following are valid routing paths in V6:

/groups
/groups/admin
/users/:id
/users/:id/messages
/files/*
/files/:id/*
/files-*
Copy the code

Paths matched using RegExp regex will not be valid:

/users/:id?
/tweets/:id(\d+)
/files/*/cat.jpg
Copy the code

All path matches in V6 ignore the trailing “/” on the URL. In fact,

has been removed and is invalid in V6. This doesn’t mean you don’t need to use slashes.

The path before VERSION v5 has route ambiguity

  1. Current path :”/users“,<Link to="me">Will jump<a href="/me">.
  2. Current path :”/users/“,<Link to="me">Will jump<a href="/users/me">.

React Router v6 fixes this ambiguity by removing the tail “/” :

  1. Current path :”/users“,<Link to="me">Will jump<a href="/users/me">.
  2. Current path :”/users“,<Link to=".. /me">Will jump<a href="/me">.

The form is more like the command line CD usage:

<a href="/app/dashboard/stats"> <Link to=".. /stats"> // <a href="/app/stats"> <Link to=".. /.. /stats"> // <a href="/stats"> <Link to=".. /.. /.. // <a href="/stats"> /stats // pwd is /app/stats cd .. /.. /stats // pwd is /stats cd .. /.. /.. /stats // pwd is /statsCopy the code

conclusion

Reference article:

  1. [A Sneak Peek at React Router v6

] (alligator. IO/react/react…

  1. What’s new in React Router v6
  2. React Router v6 in Three Minutes
  3. Migrating React Router v5 to v6

❤️ Read three things

If you find this article inspiring, I’d like to invite you to do me three small favors:

  1. Like, so that more people can see this content (collection does not like, is a rogue -_-)
  2. Pay attention to “front-end persuaders” and share original knowledge from time to time.
  3. Look at other articles as well

Personal wechat: Huab119

You can also get all the posts from my GitHub blog:

Front-end persuasion guide: github.com/roger-hiro/… Let’s play. ~