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

Passing "element" props to "Route" component

I have a list of route objects like this:

export const routes = [
  { path: '/about', element: About, exact: true },
  { path: '/posts', element: Posts, exact: true },
  { path: '/posts/:id', element: PostDetails, exact: true },
]

I have AppRouter component, in which I want to pass a list of my route objects as props for Route components with a map function instead of hardcoded values (commented section) like this:

const AppRouter = () => {
  return (
    <Routes>
      {routes.map(route =>
        <Route 
          path={route.path} 
          element={route.element}
          exact={route.exact}
        />
      )}
      {/* <Route path="/about" element={<About />}></Route>
      <Route exact path="/posts" element={<Posts />}></Route>
      <Route exact path="/posts/:id" element={<PostDetails />}></Route>
      <Route path="*" element={<Error />}></Route> */}
    </Routes>
  );
};

export default AppRouter;

How do I achieve this?

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 :

You could define the routes array with objects that specify the element prop as JSX. BTW, react-router-dom@6 routes are now always exactly matched, there is no exact prop.

Example:

export const routes = [
  { path: '/about', element: <About /> },
  { path: '/posts', element: <Posts /> },
  { path: '/posts/:id', element: <PostDetails /> },
];

const AppRouter = () => {
  return (
    <Routes>
      {routes.map(route =>
        <Route 
          key={route.path} 
          path={route.path} 
          element={route.element}
        />
      )}
      <Route path="*" element={<Error />} />
    </Routes>
  );
};

At this point though you have basically already defined a routes configuration object that can be passed to the useRoutes hook.

Example:

export const routesConfig = [
  { path: '/about', element: <About /> },
  { path: '/posts', element: <Posts /> },
  { path: '/posts/:id', element: <PostDetails /> },
  { path: "*", element: <Error /> },
];

const AppRouter = () => {
  const routes = useRoutes(routesConfig);
  return routes;
};
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