Come and join us!

“The Newbies of Little and Hill” provides technical information and a series of basic articles for front-end developers. For a better user experience, please move to our official website of Xiaoheshan beginners (https://xhs-rookies.com/) to learn, timely access to the latest articles.

“Code tailor”, if you are interested in our articles or would like to make some suggestions, please follow our official account “newbies of Xiaoheshan” at WeChat, and contact us. You can also view our articles on WeChat. Every suggestion or approval is a great encouragement to us

preface

In this section we will cover the React -Router configuration in React and how to use it

This article will introduce you to the following:

  • knowreact-router
  • react-routerThe basic use
  • react-routerUse advanced
  • react-router-config

Meet React – Router

Router If you are learning about router for the first time, go to the router section to learn more about it before you read about it

Note:The following content is based on React – Router V5. If it is not in line with what you are currently using, please refer to the React – Router V5

Install the react – the router:

yarn add react-router-dom

npm install react-router-dom

What is React Router?

React Router is a set of navigation components that are combined with your application in a declarative manner. Whether you want to provide bookmarkable URLs for your web applications or use composable navigation methods in React Native, React Router can be used anywhere React renders

The React -Router is a set of navigation components that are declaratively combined with your application. In other words, the React -Router is a routing library in the React architecture that manages URLs for component switching and state changes

React – Router basic use

Components in the React Router fall into three main categories:

The routerBrowserRouterHashRouter

  • BrowserRouterUsing the normal URL path, create an imageexample.com/some/pathThese are real URLs, but they require the correct configuration of the server
  • HashRouter Stores the current location inURLIn the hash part ofURLLook something likehttp://example.com/#/your/pageSince hashes are never sent to the server, this means that no special server configuration is required

The main difference between the two is the way they store URLs and communicate with the Web server

Route matchers, such as Switch and Route:

When a Switch component is rendered, it searches its Route child element for an element whose path matches the current URL, and it renders the first Route found and ignores all other routes. This means that you should put a Route that contains more specific paths before a less specific Route

Switch

Let’s look at the following routing rules:

  • When we match to a certain path, we find that there are some problems;
  • Such as/aboutAnd at the same time that the path is matched,/:useridIt was also matched, and the last oneNoMatchComponents are always matched to;
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/profile" component={Profile} />
<Route path="/:userid" component={User}/>
<Route component={NoMatch}/>

The reason? By default, any component in the React -Router that matches the Route to is rendered;

But in practice, we tend to want to have an exclusivity:

  • Once you get to the first one, you shouldn’t be able to match any more;
  • We can use it at this timeSwitchLet’s take all of thisRouteCarries on the parcel can;
<Switch>
  <Route exact path="/" component={Home} />
  <Route path="/about" component={About} />
  <Route path="/profile" component={Profile} />
  <Route path="/:userid" component={User} />
  <Route component={NoMatch} />
</Switch>

Route

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

There are three main rendering methods for Route

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

Route component

Render according to route props only if the position matches

import React from "react"; import ReactDOM from "react-dom"; import { BrowserRouter as Router, Route } from "react-router-dom"; // All route props (match, location and history) are available to User function User(props) { return <h1>Hello {props.match.params.username}! </h1>; } ReactDOM.render( <Router> <Route path="/user/:username" component={User} /> </Router>, node );

When you load using this method, the Router will usually create a new React element by calling React. CreateElement based on the given component. This means that if you render a component with an inline function here, it will create a new function every time it is rendered, i.e. unload the component and install a new component instead of updating it. So when you render components using inline functions, select the render or children method

Route render

Instead of using a component prop to create a new React element for you, you can pass in a function that is called when the position matches

import React from "react"; import ReactDOM from "react-dom"; import { BrowserRouter as Router, Route } from "react-router-dom"; // convenient inline rendering ReactDOM.render( <Router> <Route path="/home" render={() => <div>Home</div>} /> </Router>, node ); // wrapping/composing // You can spread routeProps to make them available to your rendered Component function FadingRoute({ component: Component, ... rest }) { return ( <Route {... rest} render={routeProps => ( <FadeIn> <Component {... routeProps} /> </FadeIn> )} /> ); } ReactDOM.render( <Router> <FadingRoute path="/cool" component={Something} /> </Router>, node );


has a higher priority than

, so do not call both methods in the same Route

Route children

It works the same way as <Route render>, except that it is called whether it matches or not

import React from "react"; import ReactDOM from "react-dom"; import { BrowserRouter as Router, Link, Route } from "react-router-dom"; function ListItemLink({ to, ... rest }) { 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>,  node );

Note that <React children> has a higher priority than either of the above two

All three render methods deliver the same route props

  • Match: contains <Route path>URLThe information of
  • Location: Represents the current location of the application
  • History: Used to manage session history in JavaScript in various ways

Route navigation, e.g. LINK, NAVLINK, REDIRECT

  • <Link>Component creates links in your application. Wherever it is presented<Link>, the anchor points will be present atHTMLAnd it will eventually be rendered asaThe element
  • NavLinkLinkAdd some style properties to the base, when thepropWhen matched to the current location, it can be set to oneactiveClassNameThe (selected) style.
  • You can use it any time you want to force navigation<Redirect>When rendering<Redirect>Will be based onproptoValue for navigation.
NavLink

When the path is selected, the corresponding a element turns red

  • activeStyle: Style when active (when matching);
  • activeClassName: Class added while active;
  • exact: Whether it is accurately matched;
<NavLink to="/" activeStyle={{color: "red"}}>home</NavLink>
<NavLink to="/about" activeStyle={{color: "red"}}>about</NavLink>
<NavLink to="/profile" activeStyle={{color: "red"}}>profile</NavLink>

However, we will notice that when the About or Profile is selected, the first one will also turn red:

  • The reason is that the/path is also matched/about/profile
  • At this time, we can in the firstNavLinkTo add onexactattribute
<NavLink exact to="/" activeStyle={{ color: 'red' }}>
  home
</NavLink>

Default ActiveClassName:

  • In fact, when the default match is successful,NavLinkI’ll add a dynamic oneactive class;
  • So we can also write styles directly
a.active {
  color: red;
}

Of course, if you’re worried about the class being used elsewhere and cascading styles, you can also customize the class

<NavLink exact to="/" activeClassName="link-active">home</NavLink>
<NavLink to="/about" activeClassName="link-active">about</NavLink>
<NavLink to="/profile" activeClassName="link-active">profile</NavLink>
Redirect

Redirect is used to Redirect a route, and when this component appears, it performs a jump to the corresponding to the “to” path. The most common scenario for Redirect is authentication

  • User browser inputUserinterfaceurl;
  • If the user is not logged in, redirect to the login page. If you are logged in, you can enterUserinterface

App.js defines the Route corresponding to the Login page in advance:

<Switch> ... Other Route <Route path="/login" component={login} /> <Route component={noMatch} /> </Switch>

Write the corresponding logical code in User.js:

import React, { PureComponent } from 'react' import { Redirect } from 'react-router-dom' export default class User extends PureComponent { constructor(props) { super(props) this.state = { isLogin: false, } } render() { return this.state.isLogin ? (</div> </div> </div>) : (<Redirect to="/login" />)}}

React – Router Advanced Use

Embedded routines by

This example shows how nested routing works. Routing/Topics loads the Topics component, which conditionally renders any further

based on the path :id value.

import React from "react"; import { BrowserRouter as Router, Switch, Route, Link, useRouteMatch, useParams } from "react-router-dom"; export default function App() { return ( <Router> <div> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> <li> <Link to="/topics">Topics</Link> </li> </ul> <Switch> <Route path="/about"> <About /> </Route> <Route path="/topics"> <Topics /> </Route> <Route path="/"> <Home /> </Route> </Switch> </div> </Router> ); } function Home() { return <h2>Home</h2>; } function About() { return <h2>About</h2>; } function Topics() { let match = useRouteMatch(); return ( <div> <h2>Topics</h2> <ul> <li> <Link to={`${match.url}/components`}>Components</Link> </li> <li> <Link To = ${match. Url} {` / props - v - state `} > props v. state < / Link > < / li > < / ul > {/ * switchable viewer has its own page < Switch >, It contains more routes based on the /topics URL path. You can think of the second <Route> here as an "index" page for all topics, */} <Switch> <Route path={' ${match.path}/:topicId}> <Topic /> </Route> <Route path={match.path}> <h3>Please select a topic.</h3> </Route> </Switch> </div> ); } function Topic() { let { topicId } = useParams(); return <h3>Requested topic ID: {topicId}</h3>; }

Dynamic routing

When we talk about dynamic routing, we mean the routing that occurs when your application is rendered, not configured or agreed upon outside of the running application.

This means that almost everything is a component in the React Router. Here’s a review of the API to see how it works:

First, grab a Router component for the environment you want to locate and render it at the top of the application.

// react-dom (what we'll use here)
import { BrowserRouter } from "react-router-dom";

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  el
);

const App = () => (
  <div>
    <nav>
      <Link to="/dashboard">Dashboard</Link>
    </nav>
    <div>
      <Route path="/dashboard" component={Dashboard} />
    </div>
  </div>
);

The Route will render the
, where props are router-specific things like {match, location, history}. If the user is not on/dashboard, the Route will be rendered null.

react-router-config

Routing can be configured in a variety of ways, so let’s take a look at best practices from the website

// React is very good at mapping data to components. // Our Route configuration is just an array of logical "routes" with paths and component props // the same order as you did in '<Switch>'. // Route configuration const Routes = [{path: "/sandwiches", component: sandwiches}, {path: "/tacos", component: tacos, routes: [ { path: "/tacos/bus", component: Bus }, { path: "/tacos/cart", component: Cart } ] } ];

Embedded in the App

export default function App() { ReactDOM.render( <Router> <div> <ul> <li> <Link to="/tacos">Tacos</Link> </li> <li> <Link to="/sandwiches">Sandwiches</Link> </li> </ul> <Switch> {routes.map((route, i) => ( <RouteWithSubRoutes key={i} {... route} /> ))} </Switch> </div> </Router> ,document.getElementById('root') ) }

So here’s the component

function Sandwiches() { return <h2>Sandwiches</h2>; } function Tacos({ routes }) { return ( <div> <h2>Tacos</h2> <ul> <li> <Link to="/tacos/bus">Bus</Link> </li> <li> <Link  to="/tacos/cart">Cart</Link> </li> </ul> <Switch> {routes.map((route, i) => ( <RouteWithSubRoutes key={i} {... route} /> ))} </Switch> </div> ); } function Bus() { return <h3>Bus</h3>; } function Cart() { return <h3>Cart</h3>; } // A special wrapper for <Route> that knows how to handle "child" routes // by passing them to the 'routes' property of the components it renders. function RouteWithSubRoutes(route) { return ( <Route path={route.path} render={props => ( // pass the sub-routes down to  keep nesting <route.component {... props} routes={route.routes} /> )} /> ); }

Next day forecast

In this section, we learned about the React-Router components and how they complement each other. So far, we have learned all about React. In the next section, we will add a login function to the previous message board!