Skip to content

React Router

Joel Baxter edited this page Dec 11, 2018 · 1 revision

We use the react-router-dom for our frontend routing.

This module allows us to render routes conditionally, based on the current URL in the browser.

An example of this in use in our app:

  1. Our root file, index.js, loads the react-router-dom as a dependency, then renders the App as a BrowserRouter.
import React from 'react'
import { render } from 'react-dom'
import { BrowserRouter } from 'react-router-dom'
import './index.css'
import App from './components/App'
import * as serviceWorker from './serviceWorker'

render((
  <BrowserRouter>
    <App />
  </BrowserRouter>
), document.getElementById('root'))
  1. Our App loads the header and Main, which contains the main content for our app.
import React, { Component } from 'react'
import Main from './Main'

export default class App extends Component {

  render () {
    return (
      <div className="App">
        <header className="App-header">
        </header>
        <Main />
      </div>
    )
  }
}
  1. The Main component loads the Switch and Route components from react-router-dom, then uses the Switch to conditionally render the Calendar component when we visit the /calendar URL.
import React, { Component } from 'react'
import Calendar from './Calendar'
import { Switch, Route } from 'react-router-dom'

export default class Main extends Component {

  render () {
    return (
      <main>
        <Switch>
          <Route exact path='/calendar' component={Calendar}/>
        </Switch>
      </main>
    )
  }
}
  1. We visit http://localhost:3000/calendar and our calendar loads. Woop!!

Clone this wiki locally