How to use useParams() with nested route

Viewed 1118

How to use URL parameters with nest routed ?

Hello, I want to build an e-commerce page which shows a single product.

So, I use useParams() to extract props from URL and use filter() to render single item.

But the 3rd party API return me an ID with slash symbol.

e.g.

{
  [
    id: 'electronics/2020/product1'
  ],
  [
    id: 'sportwear/product2'
  ]
}

When I get data from useParams(), it will return only electronics or sportwear. Not the entire ID

How to get the entire ID from using React Router DOM

P.S. Do I miss something ? Do I have to use useRouthMatch() ?


My files

// Route
<Route path="/view/:id" component={SingleProduct} />

// Link from map()

state.map(product => <Link to={product.id}>{product.title}</Link>);
1 Answers

From what I can tell, you've not any nested routing, and a couple of options.

Option 1

Convert the id fields to strings that don't resolve to route path segments. Use String.prototype.replaceAll to replace all the "/" with some other sentinel character, like "_".

state.map(product => (
  <Link to={product.id.replaceAll("/", "_")}>
    {product.title}
  </Link>
));

You can then later split the string on the sentinel character.

Examples:

const { id } = useParams();
  • const [section, year, product] = id.split("_"); // 'electronics/2020/product1'
    
  • const [section, product] = id.split("_");       // 'sportwear/product2'
    

Option 2

Explicitly declare routes for all the categories. Remember to order the routes from more specific to least specific when within a Switch component.

Example:

<Route
  exact
  path={[
    "/view/:section/:year/:productId", // '/view/electronics/2020/product1'
    "/view/:section/:productId"        // '/view/sportwear/product2'
  ]}
  component={SingleProduct}
/>

Access the route's match params in the SingleProduct component.

const { section, year, productId } = useParams();
Related