How to hide navbar in login page in react router

As of the latest release of React Router v6, it is no longer possible to pass a <div> component inside the Routes (v6) aka Switch(v5 or lower) to render a Navbar. You will need to do something like this:

  1. Create two Layout components. One simply renders a Nav and the other one does not. Suppose we name them
  • <WithNav />
  • <WithoutNav />
  1. You will need to import <Outlet /> from the React router and render inside the Layout components for the routes to be matched.

Then in your App or where ever you have your Router you will render like below ....


// WithNav.js (Stand-alone Functional Component)
import React from 'react';
import NavBar from 'your navbar location';
import { Outlet } from 'react-router';

export default () => {
  return (
    <>
      <NavBar />
      <Outlet />
    </>
  );
};


// WithoutNav.js (Stand-alone Functional Component)
import React from 'react';
import { Outlet } from 'react-router';

export default () => <Outlet />


// your router (Assuming this resides in your App.js)

      <Routes>
        <Route element={<WithoutNav />}>
          <Route path="/login" element={<LoginPage />} />
        </Route>
        <Route element={<WithNav />}>
          <Route path="/=example" element={<Example />} />
        </Route>
      </Routes>

LoginPage will not have a nav however, Example page will


You could structure your Routes differently so that the Login component doesn't have the Header Like

<BrowserRouter>
  <Switch>
  <div className="App">
    <Route exact path="/(login)" component={LoginContainer}/>
    <Route component={DefaultContainer}/>

  </div>
  </Switch>
</BrowserRouter>

const LoginContainer = () => (
  <div className="container">
    <Route exact path="/" render={() => <Redirect to="/login" />} />
    <Route path="/login" component={Login} />
  </div>
)


 const DefaultContainer = () => (
    <div>
    <Header toggleAlert={this.toggleAlert} />
    <div className="container">
      <Navbar />
      <Route path="/main" component={Main} />
      <Route path="/user" component={User} />
      <Route path="/hw-setting" component={Setting} />
      <Route path="/hw-detail/:id" component={HwDetail} />
      <Route path="/gas-detail/:id" component={GasDetail} />
      {this.state.isAlertOpen ? <Alert /> : null}
    </div>
    </div>
 )

Simplest way is use div tag and put components in which you want navbar and put login route component outside div tag:

<div className="App">
  <Router>

    <Switch>
      <Route exact path="/" component={Login} />
      <div>
        <NavBar />
   
        <Route exact path="/addproduct" component={Addproduct}></Route>
        <Route exact path="/products" component={Products}></Route>
     
      </div>

    </Switch>
  </Router>

</div>