How can I only render the breadcrumbheader component on homepage and version page? I don't want it to display on the not found page. I am using outer route with outlet because I need to access to useLocation hook in breadcrumb header and this is the only way to achieve that.
<div className="App">
<Routes>
<Route
element={
<>
<Header />
<BreadcrumbHeader />
<Outlet />
</>
}
>
<Route path="/" element={<HomePage />} />
<Route path="/version/:Id" element={<VersionPage />} />
<Route path="*" element={<NotFoundPage />} />
</Route>
</Routes>
</div>
CodePudding user response:
You can use another layout component to wrap the HomePage
and VersionPage
components so they are rendered with the BreadcrumbHeader
.
<div className="App">
<Routes>
<Route
element={(
<>
<Header />
<Outlet />
</>
)}
>
<Route
element={(
<>
<BreadcrumbHeader />
<Outlet />
</>
)}
>
<Route path="/" element={<HomePage />} />
<Route path="/version/:Id" element={<VersionPage />} />
</Route>
<Route path="*" element={<NotFoundPage />} />
</Route>
</Routes>
</div>
CodePudding user response:
2 ways :
useLocation and compare the location.path on your BreadCrumb component, something like =>
const location = useLocation() render( <> {location.path === 'toto' && } </> )
If you have just 2 or 3 routes, it's "ok", if you want more...
nested routes !! much better practice =>
<Route path="/" element={}> <Route path="/version/:id" element={} /> // other routes with breadC
You create a component ContainerWithBreath, you put the component BreadC here, don't forget to use (see the doc, it's like says "put the nested component here").
see doc part "nesting routes" for more explain
// Edit So in fact, nesting routes is a route with subRoutes, for example : /user is routes /user/profil is subRoutes
So for that, you use Route component that take path='/user' and render a component like container with your component similar for each of subRoutes. Children of this route, you put new component route, with the sub page.
In your case
<Route path="/" element={<ContainerWithB />} >
<Route path="/version/:Id" element={<VersionPage />} />
<Route index element={<Home />} />
</Route>
First line render container (you need to place on the render of ContainerWithB to display the nested route element . Second line your VersionPage Third line your Home page for '/'
Better ?