简体   繁体   中英

Nested index route not rendering in react-router-dom v6

I have a create-react-app project with react-router-dom v6 installed. Trying to use the new index route syntax so that my HomePage component renders at the index that is currently serving a Layout component. When I navigate to the index (http://localhost:3000/), it renders the Layout component with site name in an but not the HomePage component (The "Home Page" does not render).

Thanks for the help!

Code below:

App.js

import './App.css';
import {Routes, Route, Outlet, Link, BrowserRouter as Router} from "react-router-dom";

import Layout from "./components/layout/Layout";
import HomePage from "./pages/Home";

function App() {

  return (
    <div className="App">
        <Router>
            <Routes>
                <Route path="/" element={<Layout />}>
                    <Route index element={<HomePage />} />
                </Route>
            </Routes>
        </Router>
        <Outlet />
    </div>
  );
}

export default App;

Home.js

const HomePage = () => {
    return (
        <div>
            <h1>Home Page</h1>
        </div>
    )
}

export default HomePage

Layout.js

import data from "../../config/siteconfig.json"

const settings = data.settings;

const Layout = ({children}) => {
    return (
        <div>
            <h1>{settings.sitename}</h1>
            {children}
        </div>
    )
}

export default Layout

If you want nested Route components to render then the Layout component should render an Outlet for them to be rendered into. Using children prop would be if Layout was directly wrapping children components.

In other words, it is the difference between

<Route
  path="/"
  element={(
    <Layout>
      <HomePage /> // <-- rendered as children
    </Layout>
  )}
/>

and

<Route path="/" element={<Layout />}>
  <Route index element={<HomePage />} /> // <-- rendered as nested route
</Route>

Suggested code update:

import { Outlet } from 'react-router-dom';

const Layout = ({children}) => {
  return (
    <div>
      <h1>{settings.sitename}</h1>
      <Outlet />
    </div>
  );
};

...

function App() {
  return (
    <div className="App">
      <Router>
        <Routes>
          <Route path="/" element={<Layout />}>
            <Route index element={<HomePage />} />
          </Route>
        </Routes>
      </Router>
    </div>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM