Home > Net >  React Router dom returning empty object
React Router dom returning empty object

Time:10-24

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,
    },
]

CodePudding user response:

You're using component as function but they are JSX.Elements.

Try to use as

<Route key={path} path={path} element={<component />}/>

And don't forget to place key.

CodePudding user response:

I think you have a problem because if you don't use <Routes>.

function App() {
    return (
        <Provider store={store}>
            <ThemeProvider theme={theme}>
                <Routes>
                    <PageNav/>
                    <Route key={path} path={path} element={<component />}/>
                </Routes>
            </ThemeProvider>
        </Provider>
    );
}

You can view this link

CodePudding user response:

as @dogukyilmaz mentioned, components are not functions. Passing component value to the Route component prop directly won't make the deal. On the other hand, passing React.createElement(component) makes it.

  • Related