React Five

Routing

Multi-page vs Single-page

Multi-page applications traditionally store html files in the database that get requested when a user requests a different page. React creates single-page applications, meaning there is only one html file.

React Router DOM

To solve the issue of making a single-page application seem like it has multiple pages, we can use the react-router-dom package. To install it, run the following command:

npm install react-router-dom

React Router DOM Setup

Once installed, we have access to four important pieces of the react-router-dom package: HashRouter, Switch, Route, and Link.

HashRouter

HashRouter is wrapped around the entire application to provide the ability to move from 'page to page'.

//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: Exact means the path has to exactly match, which is great for 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, to make routes more dynamic. To include params, you will need to change your Route and your Link:

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

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

define param

pass in value

Made with Slides.com