React Router Tutorial For Beginners with Examples 2019

React router tutorial for beginners with examples from Coding compiler. The purpose of this react router tutorial is to explain the conceptual model when using the React Router. We call it “dynamic routing,” which is quite different from the “static routing” you might be more familiar with. Let’s start learning react router with code examples.

Static Route

If you’ve used Rails, Express, Ember, Angular, etc., you should be familiar with static routing. In these frameworks, your route is declared as part of the application initialization before any rendering occurs. React Router pre-v4 is also static (mainly). Let’s see how to configure routing with express:

app.get("/", handleIndex);
app.get("/invoices", handleInvoices);
app.get("/invoices/:id", handleInvoice);
app.get("/invoices/:id/edit", handleInvoiceEdit);
app.listen();

Notice how the route is declared before the application listens. The client routers we use are very similar. In Angular, you declare your routes first and then import them to the top before rendering AppModule:

const appRoutes: Routes = [
 {
   path: "crisis-center",
   component: CrisisListComponent
 },
 {
   path: "hero/:id",
   component: HeroDetailComponent
 },
 {
   path: "heroes",
   component: HeroListComponent,
   data: { title: "Heroes List" }
 },
 {
   path: "",
   redirectTo: "/heroes",
   pathMatch: "full"
 },
 {
   path: "**",
   component: PageNotFoundComponent
 }
];
@NgModule({
 imports: [RouterModule.forRoot(appRoutes)]
})
export class AppModule {}

Ember has a traditional routes.js file, build, read, and as you import into the application. Again, this happens before your application renders.

Related Tutorial: Vuejs Tutorial

Router.map(function() {
 this.route("about");
 this.route("contact");
 this.route("rentals", function() {
   this.route("show", { path: "/:rental_id" });
 });
});

export default Router;

Although the APIs are different, their patterns are “static routes.” The React Router also maintains this mode until it is upgraded to the v4 version.To successfully use React Router, you need to forget this mode! 😮

Background story

Frankly, we are very frustrated with the direction we used React Router in version 2. We (Michael and Ryan) are limited by the API, and when we refactor part of React (lifecycle, etc.), we think it doesn’t match the conceptual model of React’s UI. Before we discussed how to deal with it, we were walking in the corridor of a hotel.

We asked each other: “What would it look like if we used the model discussed at the seminar to build a router?”The development process is only a few hours, we have a proof of concept, we know that this is the future of the route we want. The API we end up with is not “external” to React, an API that is made up of or is naturally placed in place with the rest of React. We think you will like it.

Dynamic Routing in React Router

When we say dynamic routing, we mean that the route that occurs when the application is rendered, not the route that occurs in a configuration or convention other than running the application. This means that almost everything is a component in a React router. Here’s a 60-second review of the API to see how it works: First, get in a target environment Router components and rendered on top of the application.

// react-native
import { NativeRouter } from "react-router-native";
// react-dom (what we'll use here)
import { BrowserRouter } from "react-router-dom";
ReactDOM.render(
 <BrowserRouter>
   <App />
 </BrowserRouter>,
 el
);

Next, link the link component to the new location:

const App = () => (
 <div>
   <nav>
     <Link to="/dashboard">Dashboard</Link>
   </nav>
 </div>
);

Finally, rendering Route to access the user /dashboard when rendering some of the user interface.
const App = () => (
 <div>
   <nav>
     <Link to="/dashboard">Dashboard</Link>
   </nav>
   <div>
     <Route path="/dashboard" component={Dashboard} />
   </div>
 </div>
);

Route The rendering <Dashboard {…props}/>, which propsare some of the unique things router looks like { match, location, history }. If the user is not in /dashboard place, it Route will be rendered null. This is all about it.

Nested Route

Many routers have some concept of “nested routing.” If you use a React Router prior to v4, you will know that it is also true! How do you “nested routes” as you move from static routing configuration to dynamic rendering routing? At the same time, how do you embed div?

 const App = () => (
 <BrowserRouter>
   {/* here's a div */}
   <div>
     {/* here's a Route */}
     <Route path="/tacos" component={Tacos} />
   </div>
 </BrowserRouter>
);
// when the url matches `/tacos` this component renders
const Tacos = ({ match }) => (
 // here's a nested div
 <div>
   {/* here's a nested Route,
           match.url helps us make a relative path */}
   <Route path={match.url + "/carnitas"} component={Carnitas} />
 </div>
);

How do you think the router doesn’t have a “nested” API? Route Just a component like div the same. Therefore, in order to embed Router div, you just … do it.Let us become more alert.

Related Tutorial: VuePress Tutorial

Responsive Route

Consider the user navigating to /invoices. Your app adapts to different screen sizes, they have a narrower window, so you can only show them a list of invoices and connect to the invoice dashboard. From there they can go deeper into the navigation.

Small Screen

url: /invoices

+----------------------+
|                      |
|      Dashboard       |
|                      |
+----------------------+
|                      |
|      Invoice 01      |
|                      |
+----------------------+
|                      |
|      Invoice 02      ||                     |
+----------------------+
|                      |
|      Invoice 03      |
|                      |
+----------------------+
|                      |
|      Invoice 04      |
|                      |
+----------------------+

On a larger screen, we want to display a master-slave relationship view where the navigation is on the left and the dashboard or specific invoice is displayed on the right.

Large Screen

url: /invoices/dashboard

+----------------------+---------------------------+
|                      |     |
|      Dashboard       |            |
|                      | Unpaid: 5   |
+----------------------+                           |
|                      | Balance: $53,543.00   |
|      Invoice 01      |            |
|                      | Past Due: 2   |

+----------------------+                           |
|                      |     |
|      Invoice 02      |            |
|                      | +-------------------+   |
+----------------------+   | | |
|                      | | + + + |   |
|      Invoice 03      | | | + |  | | |
|                      | | | | | + | + |   |
+----------------------+   | | | | | | | | |
|                      | +--+-+--+--+--+--+--+   |
|      Invoice 04      |            |
|                      |     |
+----------------------+---------------------------+

Now pause for a minute and consider the /invoices URLs of both screen sizes . Is it even a valid route for a large screen? What should we put on the right?

Large Screen

url: /invoices

+----------------------+---------------------------+
|                      |                          |
|      Dashboard |                           |
|                     |                          |
+----------------------+                       |
|                       |                           |
|      Invoice 01 |                           |
|                      |                           |
+----------------------+                       |
|                      |                          |
|      Invoice 02  |  ??? |
|                      |                          |
+----------------------+                           |
|                      |     |
|      Invoice 03      |            |
|                      |     |
+----------------------+                           |
|                      |     |
|      Invoice 04      |            |
|                      |     |
+----------------------+---------------------------+

On the big screen, it’s /invoices not a valid route, but it’s on a small screen! To make things more interesting, consider people with huge mobile phones. They may look in the portrait orientation /invoices and then rotate the phone to landscape.

Suddenly, we have enough room to display the UI interface of the master-slave relationship, so you should redirect immediately!Previous versions of React Router’s static routes did not have a truly combinable answer. However, if the route is dynamic, you can write this functionality declaratively.

If you start thinking about using routing as a UI interface instead of static configuration, then your intuition will lead you to the following code:

const App = () => (
 <AppLayout>
   <Route path="/invoices" component={Invoices} />
 </AppLayout>
);
const Invoices = () => (
<Layout>
{/* always show the nav */}
   <InvoicesNav />
   <Media query={PRETTY_SMALL}>
     {screenIsSmall =>
 screenIsSmall ? (
         // small screen has no redirect
         <Switch>
           <Route exact path="/invoices/dashboard" component={Dashboard} />
           <Route path="/invoices/:id" component={Invoice} />
         </Switch>
       ) : (
 // large screen does!
         <Switch>
           <Route exact path="/invoices/dashboard" component={Dashboard} />
           <Route path="/invoices/:id" component={Invoice} />
           <Redirect from="/invoices" to="/invoices/dashboard" />
         </Switch>
)
     }
   </Media>
 </Layout>
);

This code will automatically redirect the phone to the dashboard when the user rotates the phone from portrait to landscape. The set of valid routes changes according to the dynamic nature of the mobile device in the user’s hands.

Related Tutorial: MobX Tutorial

This is just an example. We can also discuss many other issues, but we will summarize the following recommendations: In order to make the intuition consistent with the React Router, consider the components, not the static routes. Consider how to use React’s declarative combination to solve the problem, because almost every “React Router problem” could be a “React problem.”

Basic Components of React Router

  • Router components
  • Route matching components
  • Navigation components

There are three types of components in the React Router: router components, route matching components, and navigation components.

All components you use in your web application should be imported from react-router-dom.

import { BrowserRouter, Route, Link } from "react-router-dom";

Routing

The core of each React Router application should be a router component. For Web projects, react-router-dom providing <BrowserRouter>and <HashRouter>routing.

Both routes will be created for you a special history object. In general, if you have a server that responds to requests, you should use it <BrowserRouter>, if you are using a static file server, you should use it <HashRouter>.

import { BrowserRouter } from "react-router-dom";
ReactDOM.render(
 <BrowserRouter>
   <App />
 </BrowserRouter>,
 holder
);

Route Matching

There are two route matching components: <Route>and <Switch>

import { Route, Switch } from “react-router-dom”;

Route matching is accomplished by comparing <Route>the path properties and current addresses path name to achieve.

Related Tutorial: Babel Tutorial

When a <Route>match is successful, it will render its contents, when it does not match will be rendered null. There is no path <Route>will always be matched.

// when location = { pathname: '/about' }
<Route path='/about' component={About}/> // renders <About/>
<Route path='/contact' component={Contact}/> // renders null
<Route component={Always}/> // renders <Always/>

You can add it wherever you want to render content based on the address <Route>. It listed a number of possible <Route>and arrange it often makes sense. <Switch>For the <Route>grouping.

<Switch>
 <Route exact path="/" component={Home} />
 <Route path="/about" component={About} />
 <Route path="/contact" component={Contact} />
</Switch>

<Switch>Not grouped <Route>necessary, but he often useful. A <Switch>will traverse all of its child <Route>elements, and rendered with only the first element that matches the current address.

This helps the paths of multiple routes match the same pathname, when the animation transitions between routes, and no route matches the current address (so you can render a “404” component).

<Switch>
 <Route exact path="/" component={Home} />
 <Route path="/about" component={About} />
 <Route path="/contact" component={Contact} />
 {/* when none of the above match, <NoMatch> will be rendered */}
 <Route component={NoMatch} />
</Switch>

Route rendering properties

You have three attributes to <Route>render components: component, , render and children. You can view the <Route>documentation to understand them more, but we will focus on this component and render because it is almost always used your two.component It should be used when you want to render an existing component ( React.Component or a stateless component).

render Can only be used if the variables in the scope must be passed to the component to be rendered. You should not use inline functions have the component property to pass variables within range, because you will be unnecessary unload / reload assemblies.

const Home = () => <div>Home</div>;
const App = () => {
 const someVariable = true;
 return (
   <Switch>
     {/* these are good */}
     <Route exact path="/" component={Home} />
     <Route
path="/about"
       render={props => <About {...props} extra={someVariable} />}
     />
 {/* do not do this */}
     <Route
       path="/contact"
       component={props => <Contact {...props} extra={someVariable} />}
/>
</Switch>
 );
};

Navigation Components

React Router provides a <Link>component to create a link in your application. No matter where you render one <Link>, the anchor ( <a>) is rendered in the application’s HTML .

<Link to="/">Home</Link>
// <a href='/'>Home</a>

<NavLink>Is a special type <Link>as its toattribute and the current address match, it can be defined as “active.

"// location = { pathname: '/react' }
<NavLink to="/react" activeClassName="hurray">

 React

</NavLink>
// <a href='/react' className='hurray'>React</a>

When you want to force navigation, you can render one <Redirect>. When a <Redirect>render time, it will use its to attributes orientation.

<Redirect to="/login" />

Getting Started with React Web Application using React Router

The easiest way to get started with the React Web project is to use a tool called Create React App , a Facebook project with a lot of community help.

First, if you don’t have create-react-app, download it and let it create a new project.

npm install -g create-react-app
create-react-app demo-app
cd demo-app

Installation

React Router DOM released npm , so you can use npm or yarn to install it. We are going to use Yarn to create a React App.

yarn add react-router-dom

# or, if you’re not using yarn

npm install react-router-dom

Now, you can use any example copy / paste src/App.jsin. Basic example:

import React from 'react'
import {
 BrowserRouter as Router,
 Route,
 Link
} from 'react-router-dom'
const Home = () => (
 <div>
<h2>Home</h2>
 </div>
)
const About = () => (
<div>
   <h2>About</h2>
 </div>
)
const Topic = ({ match }) => (
 <div>
    <h3>{match.params.topicId}</h3>
 </div>
)
const Topics = ({ match }) => (
 <div>
   <h2>Topics</h2>
<ul>
     <li>
       <Link to={`${match.url}/rendering`}>
         Rendering with React
       </Link>
     </li>
     <li>
       <Link to={`${match.url}/components`}>
         Components
       </Link>
     </li>
     <li>
       <Link to={`${match.url}/props-v-state`}>
         Props v. State
</Link>
      </li>
   </ul>
    <Route path={`${match.path}/:topicId`} component={Topic}/>
   <Route exact path={match.path} render={() => (
     <h3>Please select a topic.</h3>
   )}/>
 </div>
)
const BasicExample = () => (
 <Router>
<div>
<ul>
       <li><Link to="/">Home</Link></li>
       <li><Link to="/about">About</Link></li>
       <li><Link to="/topics">Topics</Link></li>
     </ul>
 <hr/>
     <Route exact path="/" component={Home}/>
     <Route path="/about" component={About}/>
     <Route path="/topics" component={Topics}/>
   </div>
 </Router>
)

export default BasicExample

Now you can work on this project and improvise.

Related Tutorial: Rollup Tutorial

Server Rendering

Rendering on the server is a bit different because they are stateless. The basic idea is that we will app packed in a stateless <StaticRouter>instead of <BrowserRouter>in. We pass through the server URL request to route can match, and then we will discuss in the following <context>properties.

// user terminal
<BrowserRouter>
  <App/>
</BrowserRouter>
// server side (not complete code)
<StaticRouter
  Location={req.url}
  Context={context}
>
<App/>
</StaticRouter>

When you render on the client <Redirect>, the browser history will change the status, we will see a new page. In a static server environment, we can’t change the state of the app. Instead, we use the context property to find out the results of rendering.

If we find it context.url, then we know that the app has been redirected. This allows us to send the correct redirect address through the server.

const context = {}
const markup = ReactDOMServer.renderToString(
 <StaticRouter
   location={req.url}
   context={context}
>
<App/>
 </StaticRouter>
)
if (context.url) {
 // Rendered somewhere “<Redirect>”
 redirect(301, context.url)
} else {
 // After completion, send response
}

Add specific context information to the app

The router only adds context.url. But you may need some redirects that are 301 and 302. Or maybe you want to send a 404 response if some specific UI branches are rendered, or 401 responds if they are not authorized.

Related Tutorial: Parcel Tutorial

Then the context property is yours, so you can change it. Here’s how to distinguish between 301 and 302 redirects:

const RedirectWithStatus = ({ from, to, status }) => (
 <Route render={({ staticContext }) => {
   // there is no `staticContext` on the client, so
   // we need to guard against that here
   if (staticContext)
     staticContext.status = status
   return <Redirect from={from} to={to}/>
 }}/>
)
// somewhere in your app
const App = () => (
 <Switch>
   {/* some other routes */}
   <RedirectWithStatus
     status={301}
from="/users"
     to="/profiles"
   />
   <RedirectWithStatus
     status={302}
     from="/courses"
     to="/dashboard"
   />
</Switch>
)
// on the server
const context = {}
const markup = ReactDOMServer.renderToString(
<StaticRouter context={context}>
<App/>
</StaticRouter>
)
if (context.url) {
// Here you can use `context.status`
// We added RedirectWithStatus
redirect(context.status, context.url)
}

404, 401, or any other status

We can do the same thing, as mentioned above. Create a component, add some context and render it anywhere in the app to get different status codes.

const Status = ({ code, children }) => (
 <Route render={({ staticContext }) => {
   if (staticContext)
     staticContext.status = code
   return children
 }}/>
)

Now you can render anywhere in the app Status to add code to static staticContext.

const NotFound = () => (
 <Status code={404}>
   <div>
     <h1>Sorry, can’t find that.</h1>
   </div>
 </Status>
)
// somewhere else
<Switch>
 <Route path="/about" component={About}/>
 <Route path="/dashboard" component={Dashboard}/>
 <Route component={NotFound}/>
</Switch>

Integrated together

This is not a real app, but it shows the code that is normally used, and you need to put it together.

import { createServer } from 'http'
import React from 'react'
import ReactDOMServer from 'react-dom/server'
import { StaticRouter } from 'react-router'
import App from './App'
createServer((req, res) => {
 const context = {}
const html = ReactDOMServer.renderToString(
   <StaticRouter
     location={req.url}
     context={context}
   >
     <App/>
   </StaticRouter>
  )
 if (context.url) {
   res.writeHead(301, {
     Location: context.url
   })
   res.end()
 } else {
    res.write(`
     <!doctype html>
     <div id="app">${html}</div>
)
res.end()
 }
}).listen(3000)

Here is the client:

import ReactDOM from 'react-dom'
import { BrowserRouter } from 'react-router-dom'
import App from './App'
ReactDOM.render((
 <BrowserRouter>
   <App/>
 </BrowserRouter>
), document.getElementById('app'))

Data Loading in React Router

There are many different ways to solve this problem, but there are no clear best practices at the moment, so we try to combine them in any way, rather than specifying or leaning on one aspect. We are confident that routing can adapt to the requirements of your application.The main limitation is that you want to load data before rendering.

React Router export internal use matchPath static functions, in order to match the address to the route. You can use this feature on the server to help determine your data dependencies before rendering.The point of this approach is that it relies on a static routing configuration that is used to render routes and match before rendering to determine data dependencies.

const routes = [
 { path: '/',
   component: Root,
   loadData: () => getSomeData(),
 },
 // etc.
]

Then use this configuration to render your route in the app:

import { routes } from './routes'
const App = () => (
 <Switch>
   {routes.map(route => (
     <Route {...route}/>
   ))}
 </Switch>
)

Then on the server you will have code like this:

import { matchPath } from 'react-router-dom'
// inside a request
const promises = []
// use `some` to imitate `<Switch>` behavior of selecting only
// the first to match
routes.some(route => {
 // use `matchPath` here
 const match = matchPath(req.path, route)
 if (match)
    promises.push(route.loadData(match))
 return match
})
Promise.all(promises).then(data => {
 // do something w/ the data so the client
// can access it then render the app
})

Finally, the customer needs to extract the data. Again, we don’t specify a data loading mode for your app, but these are the points you need to implement.

You may be interested in React Router Config package to assist with static routing configuration to load data and server rendering.

Code Splitting in React Router

A big feature of the Web is that we don’t have to let visitors download the entire application before using it. You can think of code splitting as an incremental download application. We will use webpack , babel-plugin-syntax-dynamic-import, react-loadable to do this.

webpack built-in Dynamic Imports ; however, if you are using Babel (for example: the JSX compiled into JavaScript) then you will need to use babel-plugin-syntax-dynamic-import plug-ins. It’s just a grammar plugin, which means that Babel doesn’t do any extra conversions. It only allows Babel to syntactically analyze dynamic imports, so webpack can split them and package them. You .babelrc should:

{
 "presets": [
   "react"
 ],
 "plugins": [
   "syntax-dynamic-import"
 ]
}

react-loadable It is a high-level component for components with dynamic import. It handles all kinds of edge situations automatically and makes code splitting easy! Here is an example of how to use react-loadable examples:

import Loadable from 'react-loadable';
import Loading from './Loading';
const LoadableComponent = Loadable({
 loader: () => import('./Dashboard'),
 loading: Loading,
})
export default class LoadableDashboard extends React.Component {
 render() {
   return <LoadableComponent />;
 }
}

The above is the full introduction to it! When used only Loadable Dashboard(or any component you specify), it will be automatically loaded and rendered when the application is used.

Loader Option is a function of the actual loading assembly, and loading is displayed in the placeholder assembly loading the actual assembly.

Code Splitting and Server-Side Rendering in  React Router

react-loadable Includes server-side rendering guides . All you need to do is in your .babelrc add babel-plugin-import-inspector and your server can function properly. Here is an .babelrc

example file:

{
 "presets": [
   "react"
 ],
 "plugins": [
   "syntax-dynamic-import",
   ["import-inspector", {
     "serverSideRequirePath": true
   }]
 ]
}

Scroll Restoration  in React Router

In earlier versions of React Router, we provided out-of-the-box support for scroll restoration, and people have been looking for it since. I hope this article will help you get the content you need from scrollbars and routing!

Browser start using the history.pushState treatment scroll restoration, which is the way you use the same common browser navigation processing. It’s already working in chrome, it’s really great. This is the specification for Scroll Restoration.

Since the browser starts to handle the “default” and the application has different scrolling requirements (such as this site!), we do not provide default scrolling management. This guide should help you achieve any rolling needs you have.

Scroll to the top in  React Router

Most of the time, because your page content is very long, you only need to “scroll to the top” and keep scrolling down while browsing.

This only requires a <ScrollToTop>component can be a simple solution, it scrolls the window every time you navigate up, make sure that the property be encapsulated in the Router, so that it can access the router.

class ScrollToTop extends Component {
 componentDidUpdate(prevProps) {
   if (this.props.location !== prevProps.location) {
     window.scrollTo(0, 0);
   }
 }

 render() {
   return this.props.children;
 }
}
export default withRouter(ScrollToTop);

Then render it at the top of the app, but below the Router

const App = () => (
 <Router>
   <ScrollToTop>
     <App/>
   </ScrollToTop>
 </Router>
)
// or just render it bare anywhere you want, but just one :)
<ScrollToTop/>

If you have a tab interface that connects to the router, you may not want to scroll to the top when they switch tabs. Instead, you need to use in a specific position on <ScrollToTopOnMount>how to?

class ScrollToTopOnMount extends Component {
 componentDidMount() {
   window.scrollTo(0, 0);
 }
 render() {
   return null;
 }
}
class LongContent extends Component {
 render() {
   <div>
     <ScrollToTopOnMount />
     <h1>Here is my long content page</h1>
   </div>;
 }
}
// somewhere else
<Route path="/long-content" component={LongContent} />;

Universal solution

For a common solution (and what the browser starts to implement locally), we discussed two things:

  1. Scroll up and navigate so you don’t start scrolling to the new screen at the bottom
  2. Restores the scrolling position of windows and overflow elements when clicking “Back” and “Forward” (but not clicking on the link!)

At some point we want to publish a generic API. our target is:

<Router>
 <ScrollRestoration>
   <div>
     <h1>App</h1>

     <RestoredScroll id="bunny">
       <div style={{ height: "200px", overflow: "auto" }}>I will overflow</div>
     </RestoredScroll>
   </div>
 </ScrollRestoration>
</Router>

First, ScrollRestoration the navigation window will scroll up. Second, it will use location.key the window scroll position and RestoredScroll save the scroll position of the component to sessionStorage. Then, if ScrollRestoration or RestoredScroll when the mount assembly, from which can sessions Storage find their place.

When I don’t want window scrolling management, it’s very difficult to define an “exit” API. For example, if there are some tab navigation floats in your page content, you may not want to scroll to the top (the label may scroll out of the view!).

When I learned that chrome now manages scrolling positions for us and realizes that different applications will have different scrolling needs, I am a bit lost in our belief that we need to provide something, especially when people just want to scroll to the top.

Testing

The React Router relies on the React environment. This will affect how you can test your components by using our components.

Context

If you try to unit test in which a rendering <Link>or <Router>components, you will get some error messages and warnings about the context of the information. Although you might try to remove yourself router context, but we recommend that you wrap in your unit tests <StaticRouter>or <MemoryRouter>in.

Redux Integration with  React Router

Redux is an important part of the React ecosystem. For those who want to use both React Router and Redux, we want to integrate them as smoothly as possible.

Blocked Updates in React Router

In general, React Router and Redux work well together. Although sometimes an application can have a component that is not updated when the location changes (sub-route or active single-line links are not updated).

If this is the case:

  1. The component is connected to connect()(Comp).
  2. Components are not “routing component”, which means it’s not like this rendering: <Route component={SomeConnectedThing}/>.

The problem is that Redux is implemented shouldComponentUpdate, and if he does not receive the attribute from the router, there is no sign of any change. This is easy to solve. You find connectthe location of your components, then withRouterit is surrounded.

// before
export default connect(mapStateToProps)(Something)

// after
import { withRouter } from 'react-router-dom'
export default withRouter(connect(mapStateToProps)(Something))

React Router Deep integration with other Tools

Some people want to:

  • Synchronize routing data with storage and access routing data from storage
  • Ability to navigate through scheduling operations
  • Support time migration debugging of routing changes in Redux development tools

All of this requires a deeper level of integration. Please note that you do not need this deep integration:

  • Route changes are less important for time migration debugging.
  • You can pass provided to the routing component history objects, and use it to navigate in operation, rather than scheduled operation for navigation.
  • Routing data has become the backbone of most of the components you care about, whether it’s from a repository or a router, it doesn’t change the component’s code.

However, we know that some people have a strong feeling about this, so we provide the best possible deep integration. As of the 4th edition of the React Router, the Redux package has become part of the project.

Static Routes in  React Router

Previous versions of React Router used static routing to configure application routing. It allows the route to be checked and matched before rendering. Since version 4 uses dynamic components instead of path configurations, some of the previous usage has become less obvious and tricky.

We are developing a package to handle static routing configurations and React Routers to continue to satisfy those use cases.

Dealing with Update Blocking in React Router

React Router There are many location-aware components that use the current location object to determine their content rendering. By default, the context model of the current React location implicitly passed to the component. When the location changes, these components should be used in the context of new location objects to re-render.

React provides two ways to optimize the rendering performance of your application: shouldComponentUpdate lifecycle methods and PureComponent.

They will prevent the component from being re-rendered unless the correct conditions are met. Unfortunately, this means that if their re-rendering is blocked, the location-aware component of the React Router may be out of sync with the current location.

React Router API

<BrowserRouter>

Use HTML5 History API record ( pushState, replace State and pop state events) <Router> to make your UI with the URL to keep pace.

<HashRouter>

Use the hash part of the URL (ie window.location.hash) of <Router> the UI and your URL to keep pace.

<Link>

Provide declarative, accessible navigation around the application.

<NavLink>

A special version that Link adds style attributes to its render elements when it matches the current URL.

<Prompt>

Re-export from the core Prompt.

<MemoryRouter>

<Router> The history of your “URL” can be saved in memory (the address bar is not read or written). Ideal for use in both test and non-browser environments, such as React Native .

<Redirect>

Render <Redirect>will navigate to a new address. This new address will overwrite the current address in the history stack, similar to the server-side (HTTP 3xx) redirect.

<Route>

The Route component is perhaps the most important component of the React Router, allowing you to understand and learn how to use it. Its most basic responsibility is to render some UI when the location matches the path of the Route.

<Router>

The Router is the underlying interface shared by all routing components. Typically, our application will use one of the advanced routers instead:

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

The most common use of the underlying <Router> situation is to keep pace with the custom of history of state management library Mobx Redux or the like. Note that instead of using the state management library, you must use the React Router, which is only used for deep integration.

<StaticRouter>

One never changes the address <Router>.

<Switch>

Render first child node matching the address <Route>or <Redirect>.

Related JavaScript Tutorials For Beginners

JavaScript Introduction Tutorials

JavaScript Basics Tutorials

 

Leave a Comment