React Router

Quick Start

The easiest way to get started with a React web project is with a Create React App. First install create-react-app if you don’t already have it, and then make a new project with it.

// if you forgot how to install the create-react-app
npm install -g create-react-app
create-react-app demo-app
cd demo-app

------------------------

// install the react-router-dom package

yarn add react-router-dom

// or, if you're not using yarn

npm install react-router-dom

Dynamic Routing

When we say dynamic routing, we mean routing that takes place as your app is rendering, not in a configuration or convention outside of a running app. That means almost everything is a component in React Router.

First, grab yourself a Router component for the environment you’re targeting and render it at the top of your app.

import { BrowserRouter } from 'react-router-dom'

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

Next, grab the link component to link to a new location:

import { Link } from 'react-router-dom'

const App = () => (
  <div>
    <nav>
      <Link to="/">Home</Link>
      <Link to="/work">Work</Link>
      <Link to="/weather">Weather</Link>
    </nav>
  </div>
);

Finally, render your Routes to show some UI when the user visits that urls:

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

const App = () => (
  <div>
    <nav>
      <Link to="/">Home</Link>
      <Link to="/work">Work</Link>
      <Link to="/weather">Weather</Link>
    </nav>
    <div>
        <Route path='/' component={Home}/>
        <Route path='/work' component={Work}/>
        <Route path='/weather' component={Weather}/>
    </div>
  </div>
);

Route Matching

Route matching is done by comparing a <Route>'s path prop to the current location’s pathname. When a <Route> matches it will render its content and when it does not match, it will render null. A <Route> with no path will always match.

You can include a <Route> anywhere that you want to render content based on the location. It will often make sense to list a number of possible <Route>s next to each other. The <Switch> component is used to group <Route>s together.

The <Switch> is not required for grouping <Route>s, but it can be quite useful. A <Switch> will iterate over all of its children <Route> elements and only render the first one that matches the current location. 

This helps when multiple route’s paths match the same pathname, when animating transitions between routes, and in identifying when no routes match the current location (so that you can render a PageNotFound component).

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

const App = () => (
  <div>
    <Switch>
        <Route path='/' component={Home}/>
        <Route path='/work' component={Work}/>
        <Route path='/weather' component={Weather}/>
        <Route component={PageNotFound}/>
    </Switch>
  </div>
);
Made with Slides.com