Julio Jimenez
Essential DevOps

Essential DevOps

react-router-dom v5 to v6 Upgrade

react-router-dom v5 to v6 Upgrade

Julio Jimenez's photo
Julio Jimenez
·Nov 6, 2021·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

This is what my app looked like after working through a Dependabot generated version bump of react-router-dom v5.

Screenshot-2017-04-06-10.55.14-1024x563.png

As to be expected with major version upgrades, there are significant changes in v6 that will affect your app's router and routes.

This article is a soft introduction into upgrading your app to v6 from the perspective of what I did to fix my own app, and may not cover all use cases. Check out React Router's full release notes.

Below is an example of a simple react-router-dom v5 router.

import React from 'react'
import { render } from 'react-dom'
import { BrowserRouter, Route, Switch } from 'react-router-dom'
import Nav from './components/nav'
import Home from './views/home'
import Dash from './views/dash'
import Profile from './views/profile'

const App = () => {
  return (
    <>
      <Nav />
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/dash" component={Dash} />
        <Route path="/profile" component={Profile} />
      </Switch>
    </>
  )
}

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

Here's the same router in v6.

import React from 'react'
import { render } from 'react-dom'
import { BrowserRouter, Routes, Route } from 'react-router-dom'
import Nav from './components/nav'
import Home from './views/home'
import Dash from './views/dash'
import Profile from './views/profile'

const App = () => {
  return (
    <>
      <Nav />
      <Routes>
        <Route exact path="/" element={<Home />} />
        <Route path="/dash" element={<Dash />} />
        <Route path="/profile" element={<Profile />} />
      </Routes>
    </>
  )
}

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

The most obvious change is the replacement of Switch with Routes.

The Route component's component prop has been replaced with element, as well as the syntax used between the curly braces, with target elements being referenced using the self-closing tag format.

I hope this article helps someone save some time when encountered with the dreaded white screen of death.

giphy.gif

That's it. Go be essential.

 
Share this