Rednirug
Rednirug

Reputation: 81

How do I make a url contain multiple sections? React

So full disclosure, I'm not sure how to ask this question properly, but I do have a decent example. I'm making a React app and I'm trying to make the url more "descriptive" I suppose.

So it starts off at Home, then I go to a Products page and the url changes from /home to /products. This part is fine.

When I want to go to a specific product from the product page, I want the url to change to /products/example instead of just /example. Do I have to specify this with the Links or is there some cleaner way to get it done?

Right now my only answer is to make the link go to /product/example and have the App.js route to the same url. I'm not sure how to properly ask this question for a Google search so I had to ask it here. If you have an idea how to specifically phrase what I'm asking, I'd appreciate that too.

Thanks in advance.

Upvotes: 1

Views: 518

Answers (1)

kennysliding
kennysliding

Reputation: 2987

I believe the example in your URL /products/example is the product name for your product. If so, this can be done in putting the product name as an URL parameter using react-router or react-router-dom if you still have not.

by declaring the route as

import { Switch, Route } from "react-router-dom";

const Router = () => (
    <Switch>
        <Route exact path="/home" component={()=>return <h1>Home</h1>} />
        <Route exact path="/products" component={()=>return <h1>Products</h1>} />
        <Route path="/products/:productName" component={props=>return <h1>props.match.params.productName</h1>} />
    </Switch>
);

export default Router;

more on that here

Upvotes: 1

Related Questions