how to navigate submenu items using React Router Dom v6

Viewed 1296

i'm creating a react app that contains sidebar with sub items.

i want to open and components under manage/ url ( like manage/sub1, manage/sub2 ).

i tried to create a nested route inside /manage but it's redirecting to again to /manage. is there any way to do this?

const App = () => (
  <div>
    <Routes>
      <Route path="/" element={<PublicRoute />}>
        <Route path="login" element={<Login />} />
      </Route>

      <Route path="/" element={<PrivateRoute />}>
        <Route path="dashboard" element={<Dashboard />} />
        <Route path="manage" element={<Manage />} />
        <Route path="sub1" element={<Sub1 />} />
        <Route path="sub2" element={<Sub2 />} />
      </Route>

    </Routes>
  </div>
);

my sidebar navigation code

<NavItem link="/manage" icon={HappinessIcon} label="Manage" hasSubItem>
 <div>
    <NavSubItem link="/sub1" label="Sub Item 1" />
    <NavSubItem link="/sub2" label="Sub Item 2" />
 </div>
</NavItem>
2 Answers

after reading the v6 documentation i figured out nesting won't help me in this situation. i just need to add manage/ in front of all the sub items.

<Route path="manage/sub1" element={<Sub1 />} />
<Route path="manage/sub2" element={<Sub2 />} />

on my sidebar navigation code

<NavItem link="/manage" icon={HappinessIcon} label="Manage" hasSubItem>
 <div>
    <NavSubItem link="/manage/sub1" label="Sub Item 1" />
    <NavSubItem link="/manage/sub2" label="Sub Item 2" />
 </div>
</NavItem>

that's all i had to do, if you know any clean solution than this let me know.

If you want to nest routes you can use a combination of layout and index routes to accomplish it.

Example:

<Routes>
  <Route element={<PublicRoute />}>
    <Route path="/login" element={<Login />} />
  </Route>
  <Route element={<PrivateRoute />}>
    <Route path="/dashboard/*">
      <Route index element={<Dashboard />} />
    </Route>
    <Route path="/manage/*">                   // layout to allow nested route matching
      <Route index element={<Manage />} />     // "/mangage"
      <Route path="sub1" element={<Sub1 />} /> // "/mangage/sub1"
      <Route path="sub2" element={<Sub2 />} /> // "/mangage/sub2"
    </Route>
  </Route>
</Routes>

If the Manage component is rendering links they can be relative links

<NavSubItem link="sub1" label="Sub Item 1" />
<NavSubItem link="sub2" label="Sub Item 2" />

Otherwise if you are rendering all the links from a single component in/at/near the root then you'll likely need to use absolute links.

<NavSubItem link="/manage/sub1" label="Sub Item 1" />
<NavSubItem link="/manage/sub2" label="Sub Item 2" />

The difference between relative and absolute links is the leading slash "/" character.

Related