React - Router v4

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > React

1 - About

React Router is a routing service that can runs:

  • client side (web)
  • server side
  • native side
Advertising

3 - Installation

If you are writing an application that will:

  • run in the browser
# It contains a binding with DOM + react router
npm install --save react-router-dom
  • not run in the browser
npm install --save react-router

4 - Component

4.1 - Router

A React router is a component that's not going to display anything until we configure a route.

In v4, there is 3 type of router:

  • The <BrowserRouter> creates a browser history. It uses the HTML5 history API (pushState, replaceState and the popstate event)
  • the <HashRouter> creates a hash history,
  • and the <MemoryRouter> creates a memory history.

Example:

<BrowserRouter>
  <div>
    .....
  </div>
</BrowserRouter>
Advertising

4.2 - Route

doc

import { BrowserRouter, Route } from 'react-router-dom'
 
render((
  <BrowserRouter>
  <div>
      {/* add the routes here */}
    <Route path='/about' component={About} />
    <Route path='/contact' component={Contact} />
  </div>
</BrowserRouter>
), document.getElementById('app'))

where;

React Router comes with a <Link /> component that lets you navigate around your application.

Link is almost identical to the a tag, except that:

  • it's aware of the Router (the back and forward browser action are working)
  • it knows if the path it links to is active so you can style it differently (activeClassName or activeStyle attribute)

Example:

import React from 'react'
import { Link } from 'react-router'
 
export default React.createClass({
  render() {
    return (
      <div>
        <h1>React Router Tutorial</h1>
 
        <ul role="nav">
          <li><Link to="/about" activeStyle={{ color: 'red' }} >About</Link></li>
          <li><Link to="/contact" activeClassName="active" >Contact</Link></li>
        </ul>
 
        {/* add this */}
        {this.props.children}
 
      </div>
    )
  }
})
  • The rendering when clicking is
// at /about
<App>
  <About/>
</App>
 
// at /repos
<App>
  <Repos/>
</App>
Advertising

NavLink is a link aware of the history. It can add a special class activeClassName or activeStyle when the link is the actual browser path.

Example:

import { NavLink } from 'react-router-dom'
 
<NavLink to="/about" activeClassName="selected">About</NavLink>

4.5 - URL Params

Consider the following URLs:

/repos/reactjs/react-router
/repos/facebook/react

These URLs would match a route path like this:

/repos/:userName/:repoName

where:

  • :name are URL parameters whose values will be made available to route components on this.props.params[name].

5 - Documentation / Reference

web/javascript/react/react-router.txt · Last modified: 2019/06/11 09:33 by gerardnico