Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Upgrading react-router-dom from Switch to Route

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading