Home > Blockchain >  Page layout broken in React Router v6
Page layout broken in React Router v6

Time:11-16

I was refactoring my React app after updating React Router to v6 and I got rid of the error I was getting in my routes, except now the desired layout is broken.

I need to include a permanent toolbar and a sidebar to be visible only in some pages. I tried to follow the docs but now the layout component is placed above all the pages it should be wrapping, not just overlapping them, but actually concealing them behind it.

The Layout component:

function Layout({ children }) {
  return (
    <div className="layout">
      <Header />
      <SidePanel />
      <div className="main" style={{ marginTop: "100px" }}>
        {children}
      </div>
    </div>
  );
}

export default Layout;

The AppRouter component:

function AppRouter() {
  return (
    <Router>
      <Routes>
        <Route path="/" exact element={<Home />} />
        <Route path="/login" element={<Login />} />
        <Route path="/sign-up" element={<SignUp />} />
        <Route element={<Layout />}>
          <Route path="/diary" element={<Diary />} />
          <Route path="/results" element={<Results />} />
          <Route path="/details" element={<Details />} />
          <Route path="/about" element={<About />} />
        </Route>
      </Routes>
    </Router>
  );
}

export default AppRouter;

CodePudding user response:

Layout should render an Outlet for the children Routes to be rendered into.

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

function Layout({ children }) {
  return (
    <div className="layout">
      <Header />
      <SidePanel />
      <div className="main" style={{ marginTop: "100px" }}>
        <Outlet />
      </div>
    </div>
  );
}

Outlet

An <Outlet> should be used in parent route elements to render their child route elements. This allows nested UI to show up when child routes are rendered.

  • Related