API

Hooks.

useHistory

The useHistory hook is used for routing navigation.

// useHistory
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Link, Route, Switch, useHistory, withRouter } from 'react-router-dom';

const Home = () = > {
  return <div>Home</div>;
};

const About = () = > {
  const history = useHistory();

  const handleClick = () = > {
    console.log(useHistory);
    history.push('/');
  };
  return (
    <>
      <div>About</div>
      <button type="button" onClick={handleClick}>
        Go home
      </button>
    </>
  );
};

const TestHomeButton = () = > {
  const history = useHistory();

  const errClick = () = > {
    console.log(useHistory);
    history.push('/');
  };
  return (
    <>
      <BrowserRouter>
        <button type="button" onClick={errClick}>Go Home (wrong way)</button>
        <h1>App</h1>
        <ul>
          <li>
            <Link to="/about">About</Link>
          </li>
          <li>
            <Link to="/">home</Link>
          </li>
        </ul>
        <Switch>
          <Route exact={true} path="/" component={Home} />
          <Route exact={true} path="/about" component={About} />
        </Switch>
      </BrowserRouter>
    </>
  );
};

ReactDOM.render(<TestHomeButton />.document.body);
    
Copy the code

Error: ‘Cannot read property ‘push’ of undefined’ because you are trying to use the history hook outside of the Router. Write functions in the corresponding component.

useLocation

This useLocation hook returns location representing the current URL object. You can think of it as a useState that returns a URL object every time the URL changes. This can be useful, for example, if you want to do something to monitor location changes when a new page loads, as in the following example:

// useLocation
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Link, Route, Switch, useLocation } from 'react-router-dom';

const Home = () = > {
  let location = useLocation();
  React.useEffect(() = > {
    console.log(location);
    // alert(' do what you like ');
  }, [location]);
  return <div>home</div>;
};

const App = () = > {
  return (
    <>
      <BrowserRouter>
        <h1>App</h1>
        <ul>
          <li>
            <Link to="/about">About</Link>
          </li>
          <li>
            <Link to="/">home</Link>
          </li>
        </ul>
        <Switch>
          <Route exact={true} path="/" component={Home} />
          <Route exact={true} path="/about" render={()= > <div>about</div>} / ></Switch>
      </BrowserRouter>
    </>
  );
};

ReactDOM.render(<App />.document.body);
Copy the code

location:

{
  hash: ' '.key: 'y01zme'.pathname: '/'.search: ' '.state: undefined,}Copy the code

Caution The device must be used within the Router; otherwise, an error message is displayed.

useParams

UseParams returns the key/value pair object of the URL parameter. Use it to get the

parameter.

// useParams
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Link, Route, Switch, useParams } from 'react-router-dom';

const About = () = > {
  let params = useParams();
  return <div>useParams: {JSON.stringify(params)}</div>;
};

const App = () = > {
  return (
    <>
      <BrowserRouter>
        <h1>App</h1>
        <ul>
          <li>
            <Link to="/about/xxxx">About</Link>
          </li>
          <li>
            <Link to="/">home</Link>
          </li>
        </ul>
        <Switch>
          <Route exact={true} path="/" render={()= > <div>home</div>} / ><Route exact={true} path="/about/:slug" component={About} />
        </Switch>
      </BrowserRouter>
    </>
  );
};

ReactDOM.render(<App />.document.body);

Copy the code

The object key depends on the path parameter /:slug of slug

useRouteMatch

The useRouteMatch hook attempts to match the current URL in the same way as

. It is most useful to access matching data without actually rendering

.\

With no arguments, a

match object is returned.

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

const About = () = > {
  let match = useRouteMatch();
  return <div>useRouteMatch: {JSON.stringify(match)}</div>;
};

const App = () = > {
  return (
    <>
      <BrowserRouter>
        <h1>App</h1>
        <ul>
          <li>
            <Link to="/about">About</Link>
          </li>
          <li>
            <Link to="/">home</Link>
          </li>
        </ul>
        <Switch>
          <Route exact={true} path="/" render={()= > <div>home</div>} / ><Route exact={true} path="/about" component={About} />
        </Switch>
      </BrowserRouter>
    </>
  );
};

ReactDOM.render(<App />.document.body);
Copy the code

match:

{
  "path":"/about"."url":"/about"."isExact":true.// Whether it matches
  "params":{}
}
Copy the code

When accepted, the argument is the same as the props argument to match, which can be a string pathname or a Route object with a component

const match = useRouteMatch({
  path: "/BLOG/:slug/".strict: true.sensitive: true
});
Copy the code

BrowserRouter

Keep the UI in sync with the URL using the HTML5historyAPI (pushState, replaceState, and PopState events).

basename

Route prefixes, properly formed Basename should have a leading slash, but no trailing slash.

<BrowserRouter basename="/calendar"> <Link to="/today"/> // renders <a href="/calendar/today"> <Link to="/tomorrow"/> //  renders <a href="/calendar/tomorrow"> ... </BrowserRouter>Copy the code

getUserConfirmation

Function for confirming navigation. Window.confirm is used by default.

<BrowserRouter getUserConfirmation={(message, callback) => {// This is default behavior const allowTransition = window.confirm(message); callback(allowTransition); }} / >Copy the code

hashType

The encoding type used for window.location.hash. Available values are:

  • "slash" – Creates hashes like # / and #/sunshine/lollipops
  • "noslash" – Creates hashes like # and #sunshine/lollipops
  • "hashbang" – Creates “Ajax crawlable” (deprecated by Google) hashes like #! / and #! /sunshine/lollipops

The default slash

children

A single child element to render.

link

Provide declarative, accessible navigation around the application.

to: string

A string representation of the link location, rendering the corresponding router using url, search, and hash attributes.

<Link to="/about">About</Link> <Link to="/courses? sort=name" />Copy the code

to: string

Objects that can have any of the following properties:

  • pathname: A string representing the path to link to.
  • search: String representation of the query parameter.
  • hash: String representation of the query parameter. Hash to place in the URL, for example, “a-hash”.
  • state: State data is to be transmitted.
<Link to={{ pathname: "/courses", search: "? sort=name", hash: "#the-hash", state: { fromDashboard: true } }} />Copy the code

to: function

Receives the status of location. Passed as an argument to the function, which should return the object or string path to.

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

replace: boolean

If true, clicking the link replaces the current entry in the history stack rather than adding a new one.

<Link to="/courses" replace />
Copy the code

innerRef: function

Starting with React Router 5.1, if you are using React 16, this API is not required because we forward ref to base A. Use regular ref instead.

<Link to="/" innerRef={node => {// 'node' indicates the DOM element // or null when unmounted}} />Copy the code

innerRef: RefObject

If you use React 16, you don’t need the API to use React. CreateRef to get the underlying ref of the component;


let anchorRef = React.createRef()

<Link to="/" innerRef={anchorRef} />
Copy the code

Use ref directly in React 16


let anchorRef = React.createRef()

<Link to="/" ref={anchorRef} />
Copy the code

component: React.Component

If you want to use your own navigation component, simply pass it through the component API.

const FancyLink = React.forwardRef((props, ref) => ( <a ref={ref} {... Props} > 💅 {props. Children} < / a >) < Link to = "/ component = {FancyLink}" / >Copy the code

others

You can also pass properties used on, such as title, ID, class name, and so on.

NavLink

A special version of that adds style attributes to render elements when they match the current URL.

<NavLink to="/about">About</NavLink>
Copy the code

activeClassName: string

Provides a class for an element when it is active. The default given element is active. This will connect to className Prop.

<NavLink to="/faq" activeClassName="selected">
  FAQs
</NavLink>
Copy the code

activeStyle: object

The style applied to an element when it is active.

<NavLink
  to="/faq"
  activeStyle={{
    fontWeight: "bold",
    color: "red"
  }}
>
  FAQs
</NavLink>
Copy the code

exact: bool

If true, the component will only be applied if there is a perfect match.

<NavLink exact to="/profile">
  Profile
</NavLink>
Copy the code

strict: bool

If true, active classes/styles are applied only if the locations match perfectly. If true, the trailing slash on the location pathname is taken into account when determining whether the location matches the current URL. See the documentation for more information.

<NavLink strict to="/events/">
  Events
</NavLink>
Copy the code

isActive: func

A function that adds additional logic to determine whether a link is active. Use this option if you want to do more than verify that the pathname of the link matches the pathname of the current URL. ActiveStyle takes effect only when isActive returns ture.

<NavLink
  to="/blog/123"
  activeStyle={{
    fontWeight: 'bold'.color: 'red',
  }}
  isActive={(match, location) = > {
    if(! match) {return false;
    }
    console.log(match, location);
    // If the event ID is odd, only active events are considered.
    const ID = Math.floor(Math.random() * 100);
    return !isNaN(ID) && ID % 2= = =1;
  }}
>
  Event 123
</NavLink>
Copy the code

location: object

IsActive compares the current historical location (usually the current browser URL). To compare with other locations, you can pass a location.

aria-current: string

The value of the current property used on the active link. Available values include:

  • "page" – used to indicate a link within a set of pagination links
  • "step" – used to indicate a link within a step indicator for a step-based process
  • "location" – used to indicate the image that is visually highlighted as the current component of a flow chart
  • "date" – used to indicate the current date within a calendar
  • "time" – used to indicate the current time within a timetable
  • "true" – used to indicate if the NavLink is active
  • "false" – used to prevent assistive technologies from reacting to a current link (a use case would be to prevent multiple aria-current tags on a single page)

Defaults to "page".

<MemoryRouter>

. Not to study

<Redirect>

Redirect to navigate to a new location. The new location overrides the current location in the history stack.

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

to: string

<Redirect to="/somewhere/else" />
Copy the code

to: object

<Redirect to={{ pathname: "/login", search: "? utm=your+face", state: { referrer: currentLocation } }} />Copy the code

push: bool

If true, the redirect will push a new entry on the history instead of replacing the current entry

<Redirect push to="/somewhere/else" />
Copy the code

from: string

From: If the path is /xx to: redirects to/XXX for example,
Redirect /old-path /new-path

<Switch> <Redirect from="/old-path" to="/new-path" /> <Route path="/new-path"> <Place /> </Route> </Switch> // <Switch> <Redirect from="/users/: ID "to="/users/profile/: ID "/ > <Route path="/users/profile/: ID "> < profile/ >  </Route> </Switch>Copy the code

exact: bool

An exact match

<Switch>
  <Redirect exact from="/" to="/home" />
  <Route path="/home">
    <Home />
  </Route>
  <Route path="/about">
    <About />
  </Route>
</Switch>
Copy the code

Note: When rendering

within

, this can only be used with from to accurately match position. For more detailed information, details reactrouter.com/web/api/Swi…

Route

The routing component is probably the most important component of the React router to help you better understand and learn how to use it. Its most basic responsibility is to render some UI when its path matches the current URL.

Route render methods

The rendering recommendation method is to use Childen, but there are other methods you can use to render something.

  • <Route component>
  • <Route render>
  • <Route children> 

At a given point, you should use only one of the rendering methods.

Route props

All three render methods pass the same three routing parameters

  • match
  • location
  • history

match

The match object contains information about how to match urls. The match object contains the following attributes:

  • params– (object) Key/value pairs parsed from the URL corresponding to the dynamic segments of the path
  • isExact – (boolean) trueIf the entire URL was matched (no trailing characters)
  • path – (string) The path pattern used to match. Useful for building nested <Route>(Used to match paths.)
  • url – (string) The matched portion of the URL. Useful for building nested <Link>

You’ll have access to match objects in various places:

  • Route component as this.props.match
  • Route render as ({ match }) => ()
  • Route children as ({ match }) => ()
  • withRouter as this.props.match
  • matchPath as the return value
  • useRouteMatch as the return value

location

Current routing information. It looks like this:

{key: 'ac3df4', // not history! pathname: '/somewhere', search: '? some=search-string', hash: '#howdy', state: { [userDefined]: true } }Copy the code

The router will provide you with a location object in a few places:

  • Route component as this.props.location
  • Route render as ({ location }) => ()
  • Route children as ({ location }) => ()
  • withRouter as this.props.location

You can provide locations instead of strings to the various places that navigate:

  • Web Link to
  • Native Link to
  • Redirect to
  • history.push
  • history.replace

You might do something like this:

<Link to="/somewhere"/> // But you can replace const location = {pathName: '/somewhere', state: { fromDashboard: true } } <Link to={location}/> <Redirect to={location}/> history.push(location) history.replace(location)Copy the code

history

React Router provides BrowserRouter and HashRouter for JavaScript to manage session history in a variety of environments.

  • “BrowserRouter” – DOM-specific implementation, useful in Web browsers that support HTML5 history apis
  • “HashRouter” – DOM-specific implementation of older Web browsers

The history object typically has the following properties and methods:

  • Length – (number) Number of entries in the history stack

  • Action – (string) Current action (PUSH, REPLACE, or POP)

  • Location – (Object) current location. May have the following attributes:

    • pathname– (string) URL path
    • search– (string) URL query string
    • hash– (string) URL hash fragment
    • state– (object) position-specific state, for examplepush(path, state)Provided when this location is pushed onto the stack. Only available in browser and memory history.
  • Push (Path, [state]) – (feature) pushes a new entry onto the history stack

  • Replace (PATH, [state]) – (function) Replaces the current entry in the history stack

  • Go (n)- (function) Moves the pointer in the history stack by the n entry

  • GoBack () – (function) equivalent to go(-1)

  • GoForward () – (function) equivalent to go(1)

  • Block (prompt)- (function) prevents navigation (see history documentation)

component

The React component that is rendered only when the position matches. It will render using [route props].

import React from "react"; import ReactDOM from "react-dom"; import { BrowserRouter as Router, Route } from "react-router-dom"; const User = (props) => { return <h1>Hello {props.match.params.username}! </h1>; } ReactDOM.render( <Router> <Route path="/user/:username" component={User} /> </Router>, node );Copy the code

When you use Component (instead of Render or children), routing is used to create a new React element from the given component React. CreateElement. This means that if you provide inline functions for ComponentProp, you will create a new component every time you render. This results in uninstalling existing components and installing new ones, not just updating existing components. For inline rendering using inline functions, use the Render or Children item (below).

render: func

The Render property allows you to easily render inline or nested components. Instead of creating a new React element with component, you can pass a function to the property that is called when the route’s path matches. The Render attribute also accepts all parameters passed in by route.

// inline
    <Route path="path" render={() = > <div>This is inline component writing</div>} / >// A nested combination
    <Route path="path" render={ props= > (
        <ParentComp>
            <Comp {. props} / >
        </ParentComp>) / >
Copy the code

Warning:

precedence,

so do not use the same

.


children: func

The children attribute is the special one among the three attributes, and its value is a function. When Route has a children attribute, this function will be executed regardless of whether the current path matches Route, and the children attribute will also accept all parameters passed by Route.

Sometimes you want to render something regardless of whether the path matches the location. In this case, you can use the children attribute. It works exactly like Render, except that it gets called whether it matches or not. The Children render method accepts all route props identical to the Component and Render methods, unless the route does not match the URL, in which case match is null. This allows you to dynamically adjust the user interface based on whether the routes match, and if the routes match, add an activation class.

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

function ListItemLink(props: any) {
  const{ to, ... rest } = props;return (
    <Route
      path={to}
      children={({ match}) = > (
        <li className={match ? 'active' :"'} >
          <Link to={to} {. rest} / >
        </li>)} / >
  );
}

ReactDOM.render(
  <Router>
    <ul>
      <ListItemLink to="/somewhere" />
      <ListItemLink to="/somewhere-else" />
    </ul>
  </Router>.document.body
);
Copy the code

Warning:

takes precedence over both

,

so do not use the same

.



import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Link, Route, Switch } from 'react-router-dom';

const About = () = > {
  return <div>component</div>;
};

const Home = () = > {
  return <div>Home</div>;
};

const App = () = > {
  let anchorRef = React.createRef();
  React.useEffect(() = > {
    console.log(anchorRef);
  }, [anchorRef]);
  return (
    <>
      <BrowserRouter>
        <h1>App</h1>
        <ul>
          <li>
            <Link to="/about" ref={anchorRef as any} >
              About
            </Link>
          </li>
          <li>
            <Link to="/">home</Link>
          </li>
        </ul>
        <Switch>{/* Render children */}<Route exact={true} path="/about" render={()= > <div>'render'</div>} component={About} children={() => <div>'children'</div>} /> {/* Render component */}<Route exact={true} path="/" render={()= > <div>'renderHome'</div>} component={Home} />
        </Switch>
      </BrowserRouter>
    </>
  );
};
ReactDOM.render(<App />.document.body);
Copy the code

It can be concluded that:

children > component > children
Copy the code

path: string | string[]

Ability to resolve any valid URL path or array of paths.

<Route path="/users/:id">
  <User />
</Route>
Copy the code
<Route path={["/users/:id", "/profile/:id"]}>
  <User />
</Route>
Copy the code

Routes without paths always match.

exact: bool

When true, it matches only if the path exactly matches location. pathName.

<Route exact path="/one">
  <About />
</Route>
Copy the code
The path Location. Pathname accurate Match?
/one /one/two true There is no
/one /one/two false Yes.

strict: bool

When true, a will only match location. pathName with a trailing slash a. When location.pathname is /one/ :

<Route strict path="/one/">
  <About />
</Route>
Copy the code
The path Location. Pathname Match?
/one/ /one There is no
/one/ /one/ Yes.
/one/ /one/two Yes.

Warning: strict can be used to enforce alocation. Pathname has no trailing slash, but in order for this to happen, exact must be true.

<Route exact strict path="/one">
  <About />
</Route>
Copy the code
The path Location. Pathname Match?
/one /one Yes.
/one /one/ There is no
/one /one/two There is no

location: object

A

element attempts to match its path to the current historical location (usually the current browser URL). However, you can also pass a location with a different apathname to match.

This is useful when you need to match a

to a location other than the current historical location, as shown in the animated transition example.

sensitive: bool

If true, if the path is case sensitive match.

<Route sensitive path="/one">
  <About />
</Route>
Copy the code
The path Location. Pathname sensitive Match?
/one /one true Yes.
/One /one true There is no
/One /one false Yes.

Router

A common low-level interface for all routing components. Typically, the application will use one of the advanced routes instead:

  • <BrowserRouter>
  • <HashRouter>
  • <MemoryRouter>
  • <NativeRouter>
  • <StaticRouter>

The most common use case for using low-level

is to synchronize custom history with state management libraries such as Redux or Mobx. Note that there is no need to use the state management library with the React Router; it is only for deep integration.

import React from 'react';
import ReactDOM from 'react-dom';
import { Router } from 'react-router';
import { createBrowserHistory } from 'history';

const history = createBrowserHistory();
console.log(history);

const App = () = > {
  return <div>app</div>;
};

ReactDOM.render(
  <Router history={history}>
    <App />
  </Router>.document.body
);
Copy the code

history: object

History objects for navigation.

import React from "react";
import ReactDOM from "react-dom";
import { createBrowserHistory } from "history";

const customHistory = createBrowserHistory();
console.log(history);

ReactDOM.render(<Router history={customHistory} />, node);
Copy the code

Object information:

children: node

The child element to render.

StaticRouter

Please click the website reactrouter.com/web/api/Sta…

Switch

Render the first matching [

] or [

].

This is different from just using a bunch<Route>What’s the difference?


It is unique in that it presents a route exclusively. In contrast, every

and position match contains a rendering. Consider these scenarios:

import { Route } from "react-router";

let routes = (
  <div>
    <Route path="/about">
      <About />
    </Route>
    <Route path="/:user">
      <User />
    </Route>
    <Route>
      <NoMatch />
    </Route>
  </div>
);
Copy the code

If the URL is /about, < about >,

, and

are all rendered because they all match the path. This is by design and allows us to

combine it into our application in various ways, such as sidebars and breadcrumbs, bootstrap tags, etc.


However, sometimes we just want to select a

for rendering. If we are in, /about we don’t want to also match /:user (or display our “404” page). Here’s how to Switch:

import { Route, Switch } from "react-router"; let routes = ( <Switch> <Route exact path="/"> <Home /> </Route> <Route path="/about"> <About /> </Route> <Route Path = "/ : user" > < user / > < / Route > matching 404 {/ * * /} < Route > < NoMatch / > < / Route > < / Switch >);Copy the code

Now, if we are at /about,

will start looking for the match

.
will match

and will stop looking for the match and render < about >. Similarly, if we render in /michaelthen

.



This is also useful for animation transitions, because the render position matching

is the same as the previous one.

} <Route /> <Route /> </Switch> </Fade> let routes = (<Route > <Switch> </Fade>); Let routes = (<Route /> <Route /> </Fade>) let routes = (<Route /> </Fade>);Copy the code

reference

English website