Skip to content
Advertisement

React router v6, group routes by feature

I am using React router v6.

THE PROBLEM:

my App.tsx is very big as it includes routes for all of the application:

Ex.

 ...
 <Route path="products/" element={<ProductsList />} />
 <Route path="products/:slug" element={<ProductView />} />
... about 300 lines

I would like to group these routes by feature so that I end up having something like this:

 ...
 <Route path="admin" element={<AdminRoutes />} />
 <Route path="products" element={<ProductsRoute />} />
... 

it would look cleaner and easier to read.

So far I have created something like this for the Admin section:

export const AdminRoutes = (): any => {
    return (
        <Routes>
            <Route path="admin" element={<Admin />}>
       </Routes>
)}

and I have imported it like this inside App.tsx:

...
<Route element={<AdminRoutes />} path="admin" />
...

I am expecting to see the <Admin /> component (defined in AdminRoutes), although I don’t get any errors the screen is blank.

Advertisement

Answer

export const AdminRoutes = (): any => {
    return (
        <Routes>
            <Route path="admin" element={<Admin />}>
       </Routes>
)}

Since you’re using relative paths, the actual url that this will match is /admin/admin, one comes from the top level route in App, and another from here. Assuming you wanted this to only match “/admin”, you can instead do:

<Route path="*" element={<Admin />}/> // Matches /admin
<Route path="dashboard" element={<Dashboard/>}/> // Matches /admin/dashboard

Or you could use an absolute path:

<Route path="/admin" element={<Admin />}/>
<Route path="/admin/dashboard" element={<Dashboard/>}
9 People found this is helpful
Advertisement