Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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/>}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading