Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Page layout broken in React Router v6

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading