I'm using react router dom v6. If I write routes like this:
<Routes>
<Route path='/posts' element={<Posts/>}/>
<Route path='/posts/:id' element={<PostDetails/>}/>
<Route path='/about' element={<About/>}/>
<Route path='/' element={<Main/>}/>
<Route path='*' element={<NotFound/>}/>
</Routes>
it's okay, useParams returning { id: number } in the PostDetails component.
However If I write routes like the following:
<Routes>
{routes.map(({path, component}) =>
<Route path={path} element={component()}/>
)}
</Routes>
useParams returns empty object. Why this happening?
PS: routes is an array of objects containing path & component values. The actual routes value is:
export const routes = [
{
path: '/',
component: Main,
},
{
path: '/about',
component: About,
},
{
path: '/posts',
component: Posts,
},
{
path: '/posts/:id',
component: PostDetails,
},
]
{routes.map(({path, component:Component}) => <Route path={path} element={<Component />}/>)}Componenttype? However, it seems like I understand now what's wrong. I tried this<Route path={path} element={React.createElement(component)}/>and it makes the dealcomponentvariable to capitalized form, as React expects components to have a capital first letter. Then you can use it as a normal component. (see MDN docs)