React Router : Sidebar displayed in Login Page

Viewed 506

I want to hide my sidebar on my login page, only logged user can see it, This is my code but i don't know how to hide it..

 <BrowserRouter>
        <div className="container">
          <Sidebar />
          <div className="main_content">
            <Routes>
              <Route path="/" element={<Login />} />
              <Route path="/dashboard" element={<Dashboard />} />
              <Route path="/list" element={<Contrats />} />
              <Route path="/new_contract" element={<AddContract />} />
              <Route path="/edit_contract/:id" element={<EditContract />} />
              <Route path="/contract/:id" element={<Contract />} />
              <Route path="/settings" element={<div>Settings</div>} />
              <Route path="/profile" element={<div>Profile</div>} />
              <Route path="/forbidden" element={<Forbidden />} />
              <Route path="/error" element={<ServerError />} />
              <Route path="*" element={<NotFound />} />
            </Routes>
          </div>
        </div>
      </BrowserRouter>

Does anyone have any idea how to hide it for no-authorized users ? Thank you

2 Answers

The quick and dirty way to do it would be with a simple ternary, like so:

{user.isAuth ? 
 (<Sidebar />) : 
 <></>
}

But I'm guessing a cleaner solution could be using a layout for authenticated routes and an other for the other routes.

Check out this post for something like that

let pathName = window.location.pathname
let arr = pathName.toString().split("/");
let currentPath = arr[arr.length-1];
 <BrowserRouter>
        <div className="container">

          currentPath.length>0&&<Sidebar />
          <div className="main_content">
            <Routes>
              <Route path="/" element={<Login />} />
              <Route path="/dashboard" element={<Dashboard />} />
              <Route path="/list" element={<Contrats />} />
              <Route path="/new_contract" element={<AddContract />} />
              <Route path="/edit_contract/:id" element={<EditContract />} />
              <Route path="/contract/:id" element={<Contract />} />
              <Route path="/settings" element={<div>Settings</div>} />
              <Route path="/profile" element={<div>Profile</div>} />
              <Route path="/forbidden" element={<Forbidden />} />
              <Route path="/error" element={<ServerError />} />
              <Route path="*" element={<NotFound />} />
            </Routes>
          </div>
        </div>
      </BrowserRouter>
Related