Как сделать чтобы роуты создавались из массива?

Рейтинг: 0Ответов: 1Опубликовано: 16.04.2023
export const routes = [
    {path: '/about', component: About},
    {path: '/posts', component: Posts},
    {path: '/posts/:id', component: PostsIdPage},
]

const AppRouter = () => {
  return (
        <Routes>
           {routes.map(route => 
           <Route 
            component={route.component}  
            path={route.path} 
            />
           )}
     </Routes>
  )
}

Ответы

▲ 0
export const routes = [
    {path: '/about', component: About},
    {path: '/posts', component: Posts},
    {path: '/posts/:id', component: PostsIdPage},
]

const AppRouter = () => {
  return (
    <Routes>
      {routes.map(({path, component: Component}) => 
        <Route 
          component={<Component />}  
          path={path} 
        />
      )}
     </Routes>
  )
}

Либо же:

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

const AppRouter = () => {
  return (
    <Routes>
      {routes.map(route => 
        <Route 
          component={route.component}  
          path={route.path} 
        />
      )}
     </Routes>
  )
}