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

React Router Dom v6 with Typescript

I have upgraded to react-router-dom v6 I have been using RouteComponentProps for mapping over routes as below but was wondering how to inplement this in v6

<Switch>
        {routes.map((route, index) => {
            return (
                <Route
                    key={index}
                    exact={route.exact}
                    path={route.path}
                    render={(routeProps: RouteComponentProps<any>) => (
                        <route.component {...routeProps} />
                    )}
                />
            );
        })}
    </Switch>

I know that Switch is now replaced with Routes, but tnot sure what replaces RouteComponentProps

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

>Solution :

Version 6 does not have Switch and has removed the render function too.


Instead of Switch, use Routes.

Intead of the render method, use element which is a React.ReactNode .

<Routes>
  <Route path="/" element={<Dashboard />} />
  <Route path="messages" element={<DashboardMessages />} />
  <Route path="tasks" element={<DashboardTasks />} />
  <Route path="about" element={<AboutPage />} />
</Routes>;

Only if <route.component /> is a React.ReacNode.

<Routes>
  {routes.map((route, index) => {
    return (
      <Route key={index} path={route.path} element={<route.component />} />
    );
  })}
</Routes>;

Reference:

https://reactrouter.com/docs/en/v6/components/route

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