Skip to content

React Router v5

Why React Router?

  • client side routing
    • go to another page
    • render a page given a URL
  • also do server side rendering (with Remix or Next.js)

Philosophy and Intro

uidotdev: React Router v5: Philosophy and Introduction

What is BrowserRouter?

  • Parent component
  • can pass routing props to any component
    • uses React Context
import {BrowserRouter as Router} from 'react-router-dom'

, document.getElementById('app'))

<Route> and partial matching


  • will render both Users and NewUser
<Route path="/users">
    <Users />
<Route path="/users/new">
    <NewUser />

Route's render prop

    render={({ match }) => (
      <React.Suspense fallback={<>...</>}>
        <Component id={parseInt(match.params?.id, 10)} />


Raise an alert when they try to leave

  message="You have unsaved changes, are you sure you want to leave?"

Custom Modal Component


Why withRouter HOC?

Before withRouter

  1. You passed in a component to Route
  2. Route would create a HOC and pass props history, match, location to your component
    1. so you can history.push("new/path")
import { Route } from 'react-router-dom';
<Route path="/path" component={MyComponent} />

Some components (example: Header) are in every page

  • can't wrap with a Route
import { withRouter } from 'react-router-dom';

export default withRouter(Header);

gives <Header /> access to

  • history
  • match
  • location

Why isn't history.push() changing the page?

we don't have a router wrapped around the component?

How to access history?


let history = useHistory();

Route's render prop

<Route render={({history}) => <MyComponent history={history}} /> />


Preventing transitions

Last update: 2022-09-23