Categories
React

React Router

  1. V5
    1. Dynamic Routing
    2. Primary Components
      1. <BrowserRouter>
      2. <Route>
        1. Render methods
        2. Props of render methods:
        3. Props of <Route>:
      3. <Redirect>
        1. Props:
      4. <Switch>
      5. <Link>
      6. <NavLink>
    3. Static Props
      1. history:
      2. location:
    4. Hooks
      1. useHistory
      2. useParams
      3. useLocation
    5. Utility Functions
      1. generatePath

V5

Dynamic Routing

Routing that takes place as your app is rendering, not in a configuration or convention outside of a running app.


Primary Components

<BrowserRouter>

<Router> that uses the HTML5 history API (pushStatereplaceState and the popstate event) to keep your UI in sync with the URL.

Container of other <Route>s.

import {
  BrowserRouter as Router
} from "react-router-dom";

<Router>
  <App />
</BrowserRouter>

<Route>

Its most basic responsibility is to render some UI when its path matches the current URL.

A Route is always technically “rendered” even though it’s rendering null. When the <Route>‘s path matches the current URL, it renders its children.

  <Router>
    <div>
      <Route exact path="/">
        <Home />
      </Route>
      <Route path="/news">
        <NewsFeed />
      </Route>
    </div>
  </Router>

Render methods

  • component:
    The router uses React.createElement to create a new React element from the given component
  <Router>
    <Route path="/user/:username" component={User} />
  </Router>
  • render: func
    This allows for convenient inline rendering and wrapping without the undesired remounting
  <Router>
    <Route path="/home" render={() => <div>Home</div>} />
  </Router>
  • children: func
    It works exactly like render except that it gets called whether there is a match or not.
    <Route
      path={to}
      children={({ match }) => (
        <li className={match ? "active" : ""}>
          <Link to={to} {...rest} />
        </li>
      )}
    />

Priority:

children > component > render

Props of render methods:

  • location
  • history
  • match

Props of <Route>:

  • path: string | string[]
    Routes without a path always match.
  • exact: bool
  • strict: bool
  • location: object
  • sensitive: bool

<Redirect>

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

// object "to" example: 
  {
    pathname: "/login",
    search: "?utm=your+face",
    state: { referrer: currentLocation }
  }

Props:

  • to: string or object
  • push: bool
    When true, redirecting will push a new entry onto the history instead of replacing the current one.
  • from: string
  • exact, strict and sensitive

<Switch>

Renders the first child <Route> or <Redirect> that matches the location.

props:

  • to: string | object | func
  • replace: bool
<Link to="/about">About</Link>

<Link
  to={{
    pathname: "/courses",
    search: "?sort=name",
    hash: "#the-hash",
    state: { fromDashboard: true }
  }}
/>

<Link to={location => ({ ...location, pathname: "/courses" })} />
<Link to={location => `${location.pathname}?sort=name`} />

A special version of the <Link> that will add styling attributes to the rendered element when it matches the current URL.

props:

  • className: string | func
  • activeClassName: string
  • style: object | func
  • activeStyle: object
  • isActive: func
    A function to add extra logic for determining whether the link is active. This should be used if you want to do more than verify that the link’s pathname matches the current URL’s pathname.
  • aria-current: string
  • exact, strict, location
<NavLink to="/about">About</NavLink>

<NavLink
  to="/faq"
  className={isActive =>
    "nav-link" + (!isActive ? " unselected" : "")
  }
>
  FAQs
</NavLink>

<NavLink to="/faq" activeClassName="selected">
  FAQs
</NavLink>

<NavLink
  to="/faq"
  style={isActive => ({
    color: isActive ? "green" : "blue"
  })}
>
  FAQs
</NavLink>

Static Props

history:

history is mutable!

properties:

  • length – (number) The number of entries in the history stack
  • action – (string) The current action (PUSHREPLACE, or POP)
  • location – (object) The current location.
  • push(path, [state]) – (function) Pushes a new entry onto the history stack
  • replace(path, [state]) – (function) Replaces the current entry on the history stack
  • go(n) – (function) Moves the pointer in the history stack by n entries
  • goBack() – (function) Equivalent to go(-1)
  • goForward() – (function) Equivalent to go(1)
  • block(prompt) – (function) Prevents navigation (see the history docs

location:

properties:

  • pathname – (string) The path of the URL
  • search – (string) The URL query string
  • hash – (string) The URL hash fragment
  • state – (object) location-specific state that was provided to e.g. push(path, state) when this location was pushed onto the stack. Only available in browser and memory history.

Hooks

useHistory

Give access to the history instance that you may use to navigate.

import { useHistory } from "react-router-dom";

function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

useParams

useParams returns an object of key/value pairs of URL parameters.

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

function BlogPost() {
  let { slug } = useParams();
  return <div>Now showing post {slug}</div>;
}

ReactDOM.render(
  <Router>
    <Switch>
      <Route exact path="/">
        <HomePage />
      </Route>
      <Route path="/blog/:slug">
        <BlogPost />
      </Route>
    </Switch>
  </Router>,
  node
);

useLocation

The useLocation hook returns the location object that represents the current URL. 


Utility Functions

generatePath

import { generatePath } from "react-router";

generatePath("/user/:id/:entity(posts|comments)", {
  id: 1,
  entity: "posts"
});
// Will return /user/1/posts

Ref:

https://v5.reactrouter.com/web/guides/quick-start

Leave a comment