skip to Main Content

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

Answers


  1. 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>
        </>
      );
    };
    
    Login or Signup to reply.
  2. 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>
        </>
      );
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search