React Five

React Router

ROUTING

Multi-Page Applications vs Single-Page Applications

Multi-page applications (MPAs) traditionally store separate html files that clients must request specifically from a server in order to view different pages.
 

MPA's require page reloading during use.

 

Single-page applications (SPAs) only send back one html file, and rely on routing to create views.

 

SPAs cut back on the amount of trips a client needs to make to a server, so can increase performance. 

 

SPAs can require heavier initial loading, and can be less secure. JS leaks can slow powerful devices down. 

React Router DOM

To make our single-page application seem like it has multiple pages, we'll use the react-router-dom package.

 

When using a Single-Page Application, each "page" is called a view.

 

 

 

To install react-router-dom, run the following command:

npm install react-router-dom

React Router DOM Setup

Once installed, we'll have access to four important components of the react-router-dom package:

 

HashRouter

 Switch

Route

Link

HashRouter

HashRouter is wrapped around the entire application to provide the ability to route from view to view.

//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {HashRouter} from 'react-router-dom';

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

import HashRouter

wrap App with HashRouter

Switch/Route

Switch and Route are used together to define what URL displays which component. This is commonly placed in a routes.js file or router.js file in the src folder:

//routes.js
import React from 'react';
import {Switch, Route} from 'react-router-dom';
import Landing from './Components/Landing';
import DashBoard from './Components/Dashboard';

export default (
    <Switch>
      <Route exact path='/' component={Landing}/>
      <Route path='/dashboard' component={DashBoard}/>
    </Switch>
);

import Switch, Route

import components

wrap routes in Switch

URL path

component to display

Note: the 'exact' keyword means the path has to match exactly, which can also be useful for setting up landing pages

Link

Link is how we navigate from route to route. It is placed in any component that needs navigation.

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

const NavBar = (props) => {
  return (
    <div>
      <Link to='/dashboard'>DashBoard</Link>
      <Link to='/about'>About</Link>
    </div>
  )
};

export default NavBar;

import Link

Use link similar to an 'a' tag

URL Path

Params

Routes can also include params, which can be used to make routes more dynamic.

 

To include params, you will need to change the Route and Link components:

<Route path='/users/:id' component={User}/>

<Link to='/users/5'>User Profile</Link>

define param

pass in value inside of Link tag

React 5

By matias_perez

React 5

React Router

  • 238