I am trying to redirect a Route on my default page with to render content from another component and have both nav elements active. If I create a nested Route on any other page except the default route, both the main nav element and the nested nav element are active; however, when I try to apply the same logic to the default home page, only nested page nav element is active.
For example, the following works where when gallery and a nested route is selected
<Routes>
<Route path="/" element={<About />} />
<Route path="gallery" element={<Gallery />} >
<Route index element={<Navigate replace to="projects" />} />
<Route path="projects" element={<Projects />} />
<Route path="HtmlCss" element={<HtmlCss />} />
<Route path="javascript" element={<Javascript />} />
<Route path="ux" element={<UX />} />
</Route>
<Route path="accessibility" element={<Accessibility />} />
</Routes>
However, when the nested Route is under the default path="/", it does not work.
<Routes>
<Route path="about" element={<About />} />
<Route path="/" element={<Gallery />} >
<Route index element={<Navigate replace to="projects" />} />
<Route path="projects" element={<Projects />} />
<Route path="HtmlCss" element={<HtmlCss />} />
<Route path="javascript" element={<Javascript />} />
<Route path="ux" element={<UX />} />
</Route>
<Route path="accessibility" element={<Accessibility />} />
</Routes>
Is there any way to make the second version work?
2
Answers
You can use
useRoutes
hook inreact-router-dom
.The
useRoutes
hook is the functional equivalent of<Routes>
, but it uses JavaScript objects instead of<Route>
elements to define your routes. These objects have the same properties as normal<Route>
elements.For example:
In the second version of your code, where the nested routes are under the default path (
path="/" element={<Gallery />}
), you can make it work by using theOutlet
component provided by React Router.The
Outlet
component acts as a placeholder where the nested routes will be rendered. By placing it inside theGallery
component, you can render the nested routes while keeping the main nav element active.Here’s an example of how you can modify your code to achieve this:
By placing the nested routes under
<Route path="/" element={<Outlet />}>
, you are instructing React Router to render the nested routes inside theOutlet
component, which is rendered within theGallery
component. This way, both the main nav element and the nested nav element will be active when accessing the nested routes.Remember to import the necessary components from React Router:
With this modification, the second version of your code should work as expected, and both the main nav element and the nested nav element will be active on the default home page.