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;
0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

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 Welcome, glad to help. Yeah, RRDv6 was a bit of a departure from v5. You may also find this answer regarding optional parameters interesting, which is close to the use case you are describing. Cheers and good luck!
Whats the best practice to handle my useParams getting a NaN on the index path?
@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();.
Thanks for the answer, I did this: const { id = 1 } = useParams();
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.