1

I want my site to display the same page for each of the above routes. Currently it displays nothing for www.mysite.com and www.mysite.com/

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Products />}>
          <Route path="/:id" element={<ProductDisplay />} />
        </Route>
      </Routes>
    </Router>
  );
}

Products component

function Products() {
  return (
    <div className="products">
      <Outlet />
    </div>
  );
}


export default Products;
Ry2254
  • 859
  • 1
  • 10
  • 19

1 Answers1

1

If you want the ProductDisplay component to render on "/" as well as "/:id" then render an additional index route that will match with the parent route path.

Example:

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Products />}>
          <Route index element={<ProductDisplay />} /> // <-- renders on "/"
          <Route path="/:id" element={<ProductDisplay />} />
        </Route>
      </Routes>
    </Router>
  );
}

See Index Routes for more details.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • 1
    I'm surprised that's the best way, I would have thought the DRY principle would mean you shouldn't do this? Thanks for taking the time to answer, I really appreciate it. – Ry2254 Oct 15 '22 at 08:19
  • @Ry2254 Welcome, glad to help. Yeah, RRDv6 was a bit of a departure from v5. You may also find this [answer](/a/70009104/8690857) regarding optional parameters interesting, which is close to the use case you are describing. Cheers and good luck! – Drew Reese Oct 15 '22 at 08:24
  • Whats the best practice to handle my useParams getting a NaN on the index path? – Ry2254 Oct 15 '22 at 08:26
  • @Ry2254 Checking for a truthy `id` value. `const { id } = useParams();` and `if (id) { .....}`. You could also use the destructuring assignment to assign a fallback value, i.e. `const { id = "the fallback value" } = useParams();`. – Drew Reese Oct 15 '22 at 08:27
  • Thanks for the answer, I did this: const { id = 1 } = useParams(); – Ry2254 Oct 15 '22 at 08:28
  • @Ry2254 lol, yeah, exactly that. Though I'd suggest using a string value to maintain any invariants since the route path params will ***always*** be a string type. – Drew Reese Oct 15 '22 at 08:28