Home > Blockchain >  How To Redirect To Home Page if User is Logged In in reactjs react-router-dom v6
How To Redirect To Home Page if User is Logged In in reactjs react-router-dom v6

Time:07-11

I want to restrict some routes if my user is logged in, if the user is logged in and tries to go to /login it would redirect him to the home page otherwise it would redirect him to the login page.

I am using Laravel API with reactjs. However when I try to accomplish what I require, it does not work, and gives me this error "Uncaught Error: [Navigate] is not a <Route> component"

I tried using <Redirect/> but it is replaced in react-router-dom v6

Here is what I tried.

import { BrowserRouter as Router, Route, Routes, Navigate} from "react-router-dom";
import Login from "./Login";

       <Router>
            <Routes>
                <Route path="/" element={<Main/>}/>
                <Route path="/login">
                    {localStorage.getItem("auth_token") ? <Navigate to="/"/> : <Route path="/login" element={<Login/>}/>}
                </Route>
                <Route path="/login">
                    {localStorage.getItem("auth_token") ? <Navigate to="/"/> : <Route path="/register" element={<Register/>}/>}
                </Route>
            
                {/* <Route path="/login" element={<Login/>}/>
                <Route path="/register" element={<Register/>}/> */}
            </Routes>
        </Router>

EDIT:

Here is what I tried based on some other stackoverflow questions, it is still not redirecting to the login page if the user is not logged in and the auth token is not found.

  <Route path="/login" element={localStorage.getItem("auth_token") ? <Navigate to="/" /> : <Login/>}/>

CodePudding user response:

Maybe, you can go inside your Main component and write this line of code, Now I don't know how you are extracting the data whether the user is logged in or not, but I had a similar situation and I used local storage to check whether the user is logged in or not

    if(!loggedInUser) {
        return <Navigate to="/login" />
    }

CodePudding user response:

You should use in this case.

<Route exact path="/login">
  {localStorage.getItem("auth_token") ? <Redirect to="/" /> : <Route path="/login" element={<Login />}/>}
</Route>

I was glad to answer you, I hope it helps you!

  • Related