React Router V6 (react-router-dom) Dynamic Routing

 React Router V6(react-router-dom) Dynamic Routing


I was trying to implement dynamic routing with router v6 similar to that with v4 . 

eg in v4

const routes = [
{ path: '/', key:"home", component: Home },
{ path: 'page1',key:"page1", component: Page1 },
{ path: 'page2', key:"page2" component: Pag2 }
];


<Route path={variable} component 

<Router>
<Switch>
{routes.map(page => (<Route key={page.key} path={page.path} component={page.component} />))}
</Switch>
</Router>

This can be achieved in router v6 using useRoutes

Router.tsx

import { useRoutes } from "react-router-dom";

import Home from "../pages/Home";
import Page1 from "../pages/Page1";
import Page2 from "../pages/Page2";

export default function Router() {
return useRoutes([
{ path: "/", element: <Home /> },
{ path: "/page1", element: <Page1 /> },
{ path: "/page2", element: <Page2 /> },
]);
}


App.tsx

import React from "react";
import { BrowserRouter } from "react-router-dom";
import Router from "./helpers/Router";
function App() {
return (
<div>
<BrowserRouter>
<Router />
</BrowserRouter>
</div>
);
}

export default App;

References:

https://reactrouter.com/en/main/hooks/use-routes


No comments:

Post a Comment