Introduction to React Router

React Router 4 is the ideal tool for linking URLs with your React application. React Router is the de facto React routing library, and it is one of the most popular projects built on top of React.

This tutorial introduces React Router 4, the last stable version

React Router is the de facto React routing library, and it is one of the most popular projects built on top of React.

The core of React is a very simple library that does not require any routing.

Routing in a single page application is a way to introduce some functions to navigate the application through links. These functions areexpectedIn a normal web application:

  1. Browser shouldChange URLWhen you navigate to other screens
  2. Deep linkIt should work fine: if you point the browser to the URL, the application should rebuild the view that was displayed when the URL was generated.
  3. ThisBrowser back (forward) buttonIt should work as expected.

Route your application navigation together with the navigation functions provided by the browser: ThisAddress BarwithNavigation buttons.

React Router provides a way to write code in order toIt will only show certain components of your app if the route matches the route you defined.

installation

withnpm:

npm install react-router-dom

Route type

React Router provides two different routes:

  • BrowserRouter
  • HashRouter

One builds a classic URL, and the other builds a URL with a hash:

https://application.com/dashboard   /* BrowserRouter */
https://application.com/#/dashboard /* HashRouter    */

Which browser to use mainly depends on the browser you need to support.BrowserRouteruseHistory API, This is a relatively new version and is not supported in IE9 and below. If you don’t have to worry about older browsers, this is recommended.

ingredient

When used with React Router, the 3 components you interact with the most are:

  • BrowserRouter, Usually aliased asRouter
  • Link
  • Route

BrowserRouterPackage all Route components.

LinkComponents-as you can imagine-are used to generate links to your route

RouteComponents are responsible for showing or hiding the components they contain.

Browser router

This is a simple example of the BrowserRouter component. You import it from react-router-dom and use it to wrap all applications:

import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter as Router } from 'react-router-dom'

ReactDOM.render( <Router> <div> <!– –> </div> </Router>, document.getElementById(‘app’) )

A BrowserRouter component can only have one child element, so we wrap all the content to be packaged in onedivelement.

The link component is used to trigger a new route. You import fromreact-router-dom, And then you can add a "link" component to point to different routes,toAttributes:

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

ReactDOM.render( <Router> <div> <aside> <Link to={/dashboard}>Dashboard</Link> <Link to={/about}>About</Link> </aside> <!– –> </div> </Router>, document.getElementById(‘app’) )

route

Now, let's add the Route component to the above code snippet to make things actually work as needed:

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

const Dashboard = () => ( <div> <h2>Dashboard</h2></div> )

const About = () => ( <div> <h2>About</h2></div> )

ReactDOM.render( <Router> <div> <aside> <Link to={/}>Dashboard</Link> <Link to={/about}>About</Link> </aside>

  <span style="color:#f92672">&lt;</span><span style="color:#a6e22e">main</span><span style="color:#f92672">&gt;</span>
    <span style="color:#f92672">&lt;</span><span style="color:#a6e22e">Route</span> <span style="color:#a6e22e">exact</span> <span style="color:#a6e22e">path</span><span style="color:#f92672">=</span><span style="color:#e6db74">'/'</span> <span style="color:#a6e22e">component</span><span style="color:#f92672">=</span>{<span style="color:#a6e22e">Dashboard</span>} <span style="color:#f92672">/&gt;</span>
    <span style="color:#f92672">&lt;</span><span style="color:#a6e22e">Route</span> <span style="color:#a6e22e">path</span><span style="color:#f92672">=</span><span style="color:#e6db74">'/about'</span> <span style="color:#a6e22e">component</span><span style="color:#f92672">=</span>{<span style="color:#a6e22e">About</span>} <span style="color:#f92672">/&gt;</span>
  <span style="color:#f92672">&lt;</span><span style="color:#960050;background-color:#1e0010">/main&gt;</span>
<span style="color:#f92672">&lt;</span><span style="color:#960050;background-color:#1e0010">/div&gt;</span>

</Router>, document.getElementById(‘app’) )

Check the following example on Glitch:https://glitch.com/edit/#!/flaviocopes-react-router-v4/

When the route is matched/, The application showsDashboardingredient.

After changing the route by clicking the "About" link,/about, The dashboard component will be deleted,onThe component has been inserted into the DOM.

noteexactAttributes. do not have thispath="/"Will also match/aboutSince/Include in the route.

Match multiple paths

You can use regular expressions to make the route respond to multiple paths becausepathCan be a regular expression string:

<Route path='/(about|who)/' component={Dashboard} />

Inline rendering

Instead of specifying onecomponentpropertyRoute, You can set onerenderpillar:

<Route
  path='/(about|who)/'
  render={() => (
    <div>
      <h2>About</h2>
      ...
    </div>
  )}
/>

Match dynamic routing parameters

You already know how to use static routing, for example

const Posts = () => (
  <div>
    <h2>Posts</h2>
    ...
  </div>
)

//… <Route exact path="/posts" component={Posts} />

This is how to handle dynamic routes:

const Post = ({match}) => (
  <div>
    <h2>Post #{match.params.id}</h2>
    ...
  </div>
)

//… <Route exact path="/post/:id" component={Post} />

In the Route component, you can find dynamic parameters in the following locationsmatch.params.

matchIt is also available in the inline rendering route, which is particularly useful in this case because we can useidParameters, used to find post data in our data source before rendering Post:

const posts = [
  { id: 1, title: 'First', content: 'Hello world!' },
  { id: 2, title: 'Second', content: 'Hello again!' }
]

const Post = ({post}) => ( <div> <h2>{post.title}</h2> {post.content} </div> )

//… <Route exact path="/post/:id" render={({match}) => ( <Post post={posts.find(p => p.id === match.params.id)} /> )} />

Download mine for freeResponse Handbook


More response tutorials: