I have problem using createBrowserRouter . the MainLayout can't read props and I don't know why

31 Views Asked by At

all exports/imports work fine. MainLayout.js file the only file in layout : the sidebar is fixed in all pages except Login, Register and Not Found. in folder layout there is just MainLayout.js


const MainLayout = (props) => {
  return (
    <>
      {/* Sidebar component is rendered on the left side */}
      <Sidebar />
       {/* Main content wrapped inside <main> tag */} 
      <main>{props.children}</main>
    </>
  );
};


Route.js file : profile, profile edit ,home (all children) are not accessible


const router = createBrowserRouter([
   
    {
      path: "/login",
      element: <Login />,
    },
    {
      path: "/register",
      element: <Register />,
    },
    {
      path: "/",
      element: <MainLayout />,
      children: [
        {
          path: "/home",
          element: <Home />,
        },
        {
          path: "/profile/:profileId",
          element: <Profile />,
          children: [
            {
              path: "/profile/:profileId/edit",
              element: <ProfileEdit />,
            },
          ],
        },
        {
          path: "/contacts/:userId",
          element: <Chat />,
        },
      ],
    },
    { path: "*", element: <ErrorPage /> },
  ]);
const Routef = () => {
  return <RouterProvider router={router} />;
};

export default Routef;

index.js file :

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
      <Route />
  </React.StrictMode>
);
2

There are 2 best solutions below

0
Abisola Morohunfolu On

While I am not entirely sure why this is not working. I think you should consider moving the children to the Layout file and have routes nested there.

  const MainLayout = (props) => {
  return (
    <>
      {/* Sidebar component is rendered on the left side */}
      <Sidebar />
       {/* Main content wrapped inside <main> tag */} 
      <main>
        <Routes>
           <Route path="/home" element={<Home />}/>
            {/* Other routes here */}
        </Routes>
       </main>
    </>
  );
};
0
Nikola Krstic On

Instead of passing a props.children between the <main>...</main> tag you should pass an <Outlet/> imported from react-router-dom. This will render child route elements that you've added in your children: [...] array.

Like this:

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

const MainLayout = (props) => {
  return (
    <>
      {/* Sidebar component is rendered on the left side */}
      <Sidebar />
      {/* Main content wrapped inside <main> tag */}
      <main><Outlet/></main>
    </>
  );
};