I have a Main component for switching between my main components using routes.
const Main = () => {
return (
<Switch>
<Route path="/" exact component={Landing} />
<Route
path="/catalog/:category/:type?/:typeOption?"
component={Catalog}
/>
<Route path="???" component={DetailedView} />
/>
</Switch>
);
};
The Catalog component is basically a list of items available in the store. When a user clicks on one of the items, I want to replace the Catalog component with a component that displays the item with all of its details. When i'm on the detailed page, the url should be the category i was on with the name of the item appended on to it.
For example - I might be on /catalog/mens/shirts/brown and when i click on an item, i would be sent to - /catalog/mens/shirts/brown/nameOfShirt. I can get the url to send the user to through the match prop, but what do i put for path of my DetailedView component?
It seems like you are looking for Nested Routing
Inside the main component, the switch would provide only the landing and catalog view.
<Switch>
<Route path="/" exact component={Landing} />
<Route
path="/catalog/:category/:type?/:typeOption?"
component={Catalog}
/>
</Switch>
Now further inside the catalog view, you can nest the detail with something like:
function Catalog({ match }) {
return (
<div>
<Route
path={match.path + '/:nameOfProduct'}
component={DetailedView}
/>
<Route
exact
path={match.path}
render={() => <h3>Render the list of items here</h3>}
/>
</div>
)
}
This way, the URL is modified to appended to what there earlier.
To handle the optional parameters, you would have to differentiate the ID for type
and product
somehow. For eg. If I have a restriction that all product IDs would start with pr
that would be like:
<Switch>
<Route path={`${match.path}/:id(pr.*)`} render={() => <p>Product</p>} />
<Route path={match.path} render={() => <p>Still Catalogue</p>} />
</Switch>
If you cannot differentiate them using a regex pattern, then you would have to add a routing parameter in the URL, making it:
/catalog/mens/shirts/product/nameOfShirt
/catalog/mens/shirts/type/product/nameOfShirt
That way you can add the Route
above the one for catalog
in the Switch
statement
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments