Home > Net >  Passing "element" props to "Route" component
Passing "element" props to "Route" component

Time:09-29

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?

CodePudding user response:

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;
};
  • Related