cssreactjslayoutreact-router-domoutlet

How to place <Login> component if I have nested all component inside Router


I was not able to figure out where to place login so that:

    <div className="App">
      <Router>
        <NavBar />
        <Routes>
          <Route path="/message" element={ <Message /> } />
          <Route path="/" exact element={ <Profile /> } />
        </Routes>
      </Router>
    </div> 
.App{
    max-width: 1000px;
    height: 100vh;
    margin: 0 auto;
    display: grid;
    grid-template-columns: .5fr 2fr;
}

is there a proper way to manage or place the component?

Design: enter image description here

    <div className="App">
      <Router>
        <Routes>
          <Route path="/login" element={<Login />} />

          <Route element={<NavBarLayout />}>
            <Route path="/message" element={<Message />} />
            <Route path="/" element={<Profile />} />
          </Route>
        </Routes>
      </Router>
    </div>

enter image description here

codesandbox.io link project code


Solution

  • Ok, I see what you are asking for... you want to render a route for the login page that doesn't include the NavBar component. For this you use what are called Layout Routes. Create a layout wrapper that includes the NavBar and an Outlet component for nested routes to be rendered into.

    Example:

    import { Outlet } from 'react-router-dom';
    
    const NavbarLayout = () => (
      <div className="Navbar">
        <NavBar />
        <Outlet />
      </div>
    );
    

    ...

    .App {
      max-width: 1000px;
      height: 100vh;
      margin: 0 auto;
    }
    
    .Navbar {
      display: grid;
      grid-template-columns: .5fr 2fr;
    }
    

    ...

    <div className="App">
      <Router>
        <Routes>
          <Route path="/login" element={<Login />} />
    
          {/* 2-column layout with navbar */}
          <Route element={<NavbarLayout />}>
            <Route path="/message" element={<Message />} />
            <Route path="/" element={<Profile />} />
          </Route>
        </Routes>
      </Router>
    </div>