I want to add Route to my Shop
component and show CollectionOverview
component but the CollectionOverview
component is not showing and there are also no errors in console.
import React from 'react';
import { Route, Routes, useLocation } from 'react-router-dom';
import CollectionsOverview from '../../Components/CollectionsOverview/CollectionsOverview';
const Shop = () => {
const location = useLocation();
return (
<div className='shop-page'>
<Routes>
<Route
exact
path={location.pathname}
element={<CollectionsOverview />}
/>
</Routes>
</div>
);
};
export default Shop;
My code is working fine without Route
but I want to add Route
.
2
Answers
When you nest routers, you don’t need the full path name. You likely only need
/
such that your Route component looks like this:The reason this works is because you likely have something like this in an ancestor component (like your App component):
So when the user visits the URL
/shop
, your Shop component loads. Now, if you use a Route component in there, everything should be relative to/shop
. This is why you can usepath="/"
inside the Shop component – react router already knows the user is at "/shop". To put it more simply, you could also do this:Note: in the above example, you would need to use the
<Outlet />
component in your Shop component. I’m not covering all of that – I’m mostly just showing you how nested routes are relative to ancestor routes. I recommend following the guides on react router’s documentation for all of the various ways of handling nested routing.There are a couple of (potential) issues at play here. First is that you are rendering a descendent route, not a nested route. Descendent routes rendered in a
Routes
component will use relative paths from the parent route, so if you are wanting to render a descendent route on the same path as the parent then its path will simply be"/"
.Example:
The second issue is that the parent route rendering
Shop
necessarily needs to specify a trailing wildcard"*"
matcher to the path so that descendent routes can also be matched and rendered.Example:
The alternative is to actually render nested routes. The nested route rendering
CollectionsOverview
would be an index route to match and render when the parent route is matched.Example: