React Router

Objectives

  • Describe React Router v4

  • Differentiate BrowserRouter vs HashRouter

  • Use Link, Switch, and Route components

React Router v4

A library to manage routing in your single page application

Version 4 was launch in March 2017 and has some big changes compared to v3

Version 4 is a declarative api that uses components to make rendering decisions

BrowserRouter vs HashRouter

BrowserRouter uses the history object and makes changes to the URL, the hash router adds hashes to the url instead

BrowserRouter

HashRouter

/

/users

/users/57492/messages

/#

/#users

/#users/57492/messages

BrowserRouter vs HashRouter

BrowserRouter requires server support

HashRouter does not require server support

Always choose BrowserRouter if you are able

React Router Install

npm install --save react-router-dom

React Router Setup

import React from 'react';
import ReactDOM from 'react-dom';
import {
  BrowserRouter as Router
} from 'react-router-dom';
import App from './App';

ReactDOM.render(
  <Router>
    <App />
  </Router>,
  document.getElementById('root')
);

Switch And Route

import React, {Component} from 'react';
import {
 Switch, Route
} from 'react-router-dom';

const Homepage = () => (<div>HOMEPAGE</div>);
const About = () => (<div>ABOUT</div>);

const SwitchDemo = () => (
  <Switch>
    <Route path="/about" component={About}/>
    <Route path="/" component={Homepage}/>
  </Switch>
);

Link

import React from 'react';
import {Link} from 'react-router-dom';
import SwitchDemo from './SwitchDemo';

const App = () => (
  <div>
    <Link to="/">HOME</Link>
    <Link to="/about">ABOUT</Link>
    <div style={{fontSize: '3em',
                 margin: '25px'}}>
      <SwitchDemo/>
    </div>
  </div>
);

NavLink

import React from 'react';
import {NavLink} from 'react-router-dom';
import SwitchDemo from './SwitchDemo';

const s={color: "red"}; //active style
const App = () => (
  <div>
    <NavLink exact activeStyle={s} to="/">
     HOME
    </NavLink>
    <NavLink exact activeStyle={s} to="/about">
      ABOUT
    </NavLink>
    <div style={{fontSize: '3em',margin: '25px'}}>
      <SwitchDemo/>
    </div>
  </div>
);