Home > Software design >  Upgrading react-router-dom from Switch to Route
Upgrading react-router-dom from Switch to Route

Time:11-15

This worked in "react-router-dom": "^5.3.0"

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

import Api from "./Api";
const api = new Api();
const App = () => {
  return (

  ...
  <Router basename="/my-app">
    <Switch>
       <Route
         path="/complete"
         render={(props) => <ConfirmationPage {...props} api={api} />}
       />

       ...
    </Switch>
  </Router>
    

After upgrading to "react-router-dom": "^6.4.3"

We've tried:

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

import Api from "./Api";
const api = new Api();
const App = () => {
  return (

  ...
  <Router basename="/my-app">
    <Routes>
       <Route
         path="/complete"
         element={(props) => <ConfirmationPage {...props} api={api} />}
       />

       ...
    </Routes>
  </Router>

But that doesn't work. We've read through https://reactrouter.com/en/6.4.3/upgrading/v5 but do not see how to handle passing in props.

CodePudding user response:

In react-router-dom@6 the route components are passed as JSX to the element prop, and passing props to the routed component works just like it does anywhere else in React.

Example:

<Router basename="/my-app">
  <Routes>
    <Route
      path="/complete"
      element={(
        <ConfirmationPage
          api={api} // <-- props passed to component
        />
      )}
    />
    ...
  </Routes>
</Router>

There are no longer any route props, so if the routed components need access to what was previously provided they will need to use the React hooks, i.e. useLocation, useNavigate, useParams, etc.

Additional documentation:

  • Related