Ry2254
Ry2254

Reputation: 1009

How to make home path display from sub-route using React Router Dom?

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;

Upvotes: 1

Views: 48

Answers (1)

Drew Reese
Drew Reese

Reputation: 203457

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.

Upvotes: 1

Related Questions