Home > Back-end >  Nested route doesn't render component
Nested route doesn't render component

Time:12-03

I have a component that needs to be rendered under the Home page component. Now I have nested, but the component is not rendered. Although if you do without nesting, then everything works. How can I do this?

export default function App() {
  return (
    <div className="App">
      <Routes>
        <Route path="/" element={<Home />}>
          <Route path="route1" element={<Route1 />} />
        </Route>
      </Routes>
    </div>
  );
}
export default function Route1() {
  return (
    <>
      <h2>Route1</h2>
      <Outlet />
    </>
  );
}
export default function Home() {
  return (
    <>
      <h1>Home Page</h1>
    </>
  );
}

CodePudding user response:

Try wrapping your Routes with Router

Link to my stackblitz and play with it..

Also, a quick read >> https://dev.to/tywenk/how-to-use-nested-routes-in-react-router-6-4jhd

import * as React from 'react';
import {
  BrowserRouter as Router,
  Route,
  Routes,
  Link,
  Outlet,
} from 'react-router-dom';

export default function App() {
  return (
    <div className="App">
      <Router>
        <nav>
          <Link to="/">Home</Link> <Link to="route1">Route 1</Link>
        </nav>
        <Routes>
          <Route path="/" element={<Home />}>
            <Route path="route1" element={<Route1 />} />
          </Route>
        </Routes>
      </Router>
    </div>
  );
}

function Route1() {
  return <h1>"In Route 1"</h1>;
}

function Home() {
  return (
    <React.Fragment>
      <h1>"In Home"</h1>
      <Outlet />
    </React.Fragment>
  );
}

Using <nav> is optional.. added just for demo.. you can use your own method for routing actions (using links, buttons, etc.)

CodePudding user response:

The Home component is rendered as a Layout Route so it should render an Outlet component for the nested routes.

export default function App() {
  return (
    <div className="App">
      <Routes>
        <Route path="/" element={<Home />}> // <-- Layout route
          <Route path="route1" element={<Route1 />} /> // <-- Nested route
        </Route>
      </Routes>
    </div>
  );
}
export default function Home() {
  return (
    <>
      <h1>Home Page</h1>
      <Outlet /> // <-- Nested routes render element here
    </>
  );
}

Route1 only needs to render an Outlet if it is also a layout route. The Outlet can be removed if this is not the case.

export default function Route1() {
  return (
    <>
      <h2>Route1</h2>
    </>
  );
}
  • Related