react-router v4

"what the hell is dynamic routing"

difference between static
and dynamic routing

static routing

  • Defined on top of application
     
  • Usually separate configuration
     
  • Set once at the beginning of the application lifecycle
     
  • Cannot be modified dynamically based on external conditions (like screen resolution)

static routing example

const appRoutes: Routes = [
  { path: 'crisis-center',
    component: CrisisListComponent
  },
  { path: 'hero/:id',
    component: HeroDetailComponent
  },
  { path: 'heroes',
    component: HeroListComponent,
    data: { title: 'Heroes List' }
  },
  { path: '',
    redirectTo: '/heroes',
    pathMatch: 'full'
  },
  { path: '**',
    component: PageNotFoundComponent
  }
];

dynamic routing

  • Integral part of the application
     
  • Can be modified during application lifetime when conditions change
     
  • Takes full advantage of component-based approach - routes are just components that render (or not) based on URL

dynamic routing example

const App = observer(function App() {
  return (
    <div id="app">
      <Switch>
        <Route path="/" exact strict component={LandingPage}/>
        <Route path="/pricing" component={Pricing}/>
        {isSignedIn() && <Route path="/dashboard" component={Dashboard}/>}
        {isMobile()   && <Route path="/settings" component={MobileSettings}/>}
        <Route component={NotFound}/>
      </Switch>
    </div>
  )
})

how to set up

react router in project

installing react-router

$ yarn add react-router-dom

# or for iOS/Android

$ yarn add react-router-native

adding <router> to app

import React from 'react'

# web
import { BrowserRouter as Router } from 'react-router-dom'

# iOS/Android
import { NativeRouter as Router } from 'react-router-native'

const App = function App() {
  return (
    <Router>
      <div id="app">
        <p>Your normal application code.</p>
        <p>You can add <Route/> components however deep you want.</p>
      </div>
    </Router>
  )
}

Check out demo app

https://github.com/d4rky-pl/react-router-demo-app

https://boiling-sierra-32676.herokuapp.com/

live

code

React Router v4

By Michał Matyas

React Router v4

  • 660