How to Update React Router in React

This article provides a straightforward guide on how to update React Router in your React applications. You will learn how to install the latest version using npm or yarn, understand the major API changes between version 5 and version 6, and successfully refactor your codebase to prevent application crashes after the upgrade.

Step 1: Install the Latest Version of React Router

To update React Router, you need to install the latest version of react-router-dom using your package manager. Run one of the following commands in your project’s root directory:

Using npm:

npm install react-router-dom@latest

Using yarn:

yarn add react-router-dom@latest

Using pnpm:

pnpm add react-router-dom@latest

Step 2: Refactor Code for React Router v6

If you are upgrading from React Router v5 to v6, several breaking changes require you to update your syntax.

1. Replace Switch with Routes

In v6, the <Switch> component has been replaced by <Routes>.

Old v5 Syntax:

import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

<Router>
  <Switch>
    <Route path="/about" component={About} />
  </Switch>
</Router>

New v6 Syntax:

import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';

<Router>
  <Routes>
    <Route path="/about" element={<About />} />
  </Routes>
</Router>

2. Update Route Elements

The component and render props on the <Route> component have been replaced by the element prop, which takes a JSX element instead of a component reference.

3. Replace useHistory with useNavigate

The useHistory hook has been deprecated and replaced by the useNavigate hook for programmatic navigation.

Old v5 Syntax:

import { useHistory } from 'react-router-dom';

const history = useHistory();
history.push('/dashboard');

New v6 Syntax:

import { useNavigate } from 'react-router-dom';

const navigate = useNavigate();
navigate('/dashboard');

Step 3: Verify the Installation

After updating the package and refactoring your code, verify the update by checking your package.json file. Ensure that react-router-dom points to the latest version. Finally, run your development server (npm start or npm run dev) to ensure there are no compilation errors or runtime console warnings.