React Router

(Continued)

Objectives

  • Use URL parameters for a Route

  • Define Route props

  • Define withRouter

  • Passing your own props to a component in Route (render vs component)

URL Parameters

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

const Homepage = () => (<div>HOMEPAGE</div>);
const Name = ({match}) => (
  <div>Hello, {match.params.name}</div>
);
const SwitchDemo = () => (
  <Switch>
    <Route path="/:name" component={Name}/>
    <Route path="/" component={Homepage}/>
  </Switch>
);

Route Props

A component inside of a Route gets 3 props

match - info about how the url matches the route component

location - where you are now, similar to window.location

history - similar to html5 history object, allows explicit changes to the url

withRouter

If a component is not rendered inside of a Route component, you can use withRouter to get route props

withRouter Example

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

const SwitchDemo = ({history}) => (
  <div>
    <Switch>
      <Route path="/:name" component={Name}/>
      <Route path="/" component={Homepage}/>
    </Switch>
    <button onClick={() => history.push('/')}>
      Go Home
    </button>
  </div>
);
export default withRouter(SwitchDemo);

Route:

Render vs Component

The route component can either use render or component (never both)

Use render to pass custom props to your component

Route Render Example

import {Route} from 'react-router-dom';
const teachers = ['Tim', 'Colt', 'Matt', 'Elie'];
const Teachers = ({teachers}) => (
  <ul>
    {teachers.map((teach, ind) => (
      <li key={i}>{teach}</li>
     ))}
  </ul>
);

const App = () => (
  <Route path="/teachers" render={props => (
    <Teachers {...props} teachers={teachers} />
  )}/>
);

React Router Docs

React Router Continued

By Elie Schoppik

React Router Continued

  • 2,417