Home > Mobile >  React router v6: How to ignore beginning path and evaluate the rest of it
React router v6: How to ignore beginning path and evaluate the rest of it

Time:05-12

I'm trying to render the component ProductDetail when the browser goes to any url that ends with /product/:productId, such as http://localhost:3000/collection/323/product/526311418

What I have until now:

import { Routes, Route } from 'react-router-dom';

const App = () => {
    return (
        <Routes>
            <Route path='/' element={<Navigation />}>
                <Route index element={<Home />} />
                <Route path='collection/:collectionId' element={<Collection />} />
                <Route path=':AnyValue*/product/:productId' element={<ProductDetail />} />
            </Route>
        </Routes>
    );
}

CodePudding user response:

react-router-dom@6 doesn't use RegExp for any path processing. You will need to explicitly define the routes you want to match.

Example:

<Routes>
  <Route path="/" element={<Navigation />}>
    <Route index element={<Home />} />
    <Route path="collection/:collectionId" element={<Collection />}> // *
      // matches "/collection/323/product/526311418"
      <Route path="product/:productId" element={<ProductDetail />} />
    </Route>
    // matches "product/526311418"
    <Route path="product/:productId" element={<ProductDetail />} />
  </Route>
</Routes>

* Note: For this Collection needs to also render an Outlet for nested routes.

Edit react-router-v6-how-to-ignore-beginning-path-and-evaluate-the-rest-of-it

  • Related