I am using React router v6.
THE PROBLEM:
my App.tsx
is very big as it includes routes for all of the application:
Ex.
JavaScript
x
5
1
2
<Route path="products/" element={<ProductsList />} />
3
<Route path="products/:slug" element={<ProductView />} />
4
about 300 lines
5
I would like to group these routes by feature so that I end up having something like this:
JavaScript
1
5
1
2
<Route path="admin" element={<AdminRoutes />} />
3
<Route path="products" element={<ProductsRoute />} />
4
5
it would look cleaner and easier to read.
So far I have created something like this for the Admin section:
JavaScript
1
7
1
export const AdminRoutes = (): any => {
2
return (
3
<Routes>
4
<Route path="admin" element={<Admin />}>
5
</Routes>
6
)}
7
and I have imported it like this inside App.tsx
:
JavaScript
1
4
1
2
<Route element={<AdminRoutes />} path="admin" />
3
4
I am expecting to see the <Admin />
component (defined in AdminRoutes
), although I don’t get any errors the screen is blank.
Advertisement
Answer
JavaScript
1
7
1
export const AdminRoutes = (): any => {
2
return (
3
<Routes>
4
<Route path="admin" element={<Admin />}>
5
</Routes>
6
)}
7
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:
JavaScript
1
3
1
<Route path="*" element={<Admin />}/> // Matches /admin
2
<Route path="dashboard" element={<Dashboard/>}/> // Matches /admin/dashboard
3
Or you could use an absolute path:
JavaScript
1
3
1
<Route path="/admin" element={<Admin />}/>
2
<Route path="/admin/dashboard" element={<Dashboard/>}
3