简体   繁体   中英

Redirect user from the dashboard page to login page when user click on logout button

Hi I have a user dashboard in which I'm showing some basic details of the users, and I have also given a logout button so onces user click on it he/she should be completely redirect to the login page, but the proble is when I'm trying to access the login page then by default the dashboard is also getting loaded.

I'm not sure where I have to add the login module into App.js

function App() {
return (
<Router>
<div className="App">
  <Topbar/>
  <div className='container'>
  <Sidebar/>
  <div className='others'>
  
  <Routes>
      <Route path="/" element={<Home/>} />
      <Route path="/createTrip" element={<CreateTrip/>} />
      <Route path="/allTrip" element={<AllTrip/>} />
      <Route path="/driverDetail" element={<DriverDetails/>} />
      <Route path="/myVehicle" element={<MyVehicle/>} />
  <Route path="*" element={<Home />} />
  </Routes>
  </div>
  </div>
  
  </div>
</Router>

); }

在此处输入图像描述

As per my understanding of your question, You want to redirect to login page once you click on logout, but instead your dashboard is rendered.

The approximation of your problem is redirection, private routing and session handling.

If you are handling user sessions (holding user login state in localStorage or in your app state), use private routes to check weather the user is logged in or not and accordingly redirect to the desired page.

In your example it would be similar to adding nested routes with private route as their parent.

Private Route -

import Navigate from "react-router-dom";
    export const PrivateRoute =({children}) => {
       if(localStorage.getItem("token")){
    return children
           } else {
                Navigate("/login")
           }
    
     }




        function App() {
    return (
    <Router>
    <div className="App">
      <Topbar/>
      <div className='container'>
      <Sidebar/>
      <div className='others'>
      
      <Routes>
          <Route path="/" element={<Home/>} />
          <Route path="/createTrip" element={<PrivateRoute><CreateTrip/></PrivateRoute>} />
          <Route path="/allTrip" element={<PrivateRoute><AllTrip/></PrivateRoute>} />
          // and so on
      </Routes>
      </div>
      </div>

      
      </div>

</Router>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM