Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

83
Vistas
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?

almost 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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;
};
almost 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda