Kindth
Kindth

Reputation: 337

How to redirect to home page after logout in React

I have a simple react app, I try to logout and redirect to the home page after that, so I don't know why it doesn't work as expected can someone help me please.

here's my code :

PrivateRoute.jsx

const PrivateRoute = ({ component: RouteComponent, ...rest }) => {
    const { currentUser } = useContext(AuthContext);
    return (
        <Route
        {...rest}
        render={
            routeProps =>
            !!currentUser ? (
                <RouteComponent {...routeProps} />
            ) :(
                <Redirect to={"/"} />
            )
        }
        />
    );
};

Navbar.jsx

  const handleLogOut = () => { 
          
        fire
            .auth()
            .signOut();
        localStorage.clear();
        console.log("Logout successful");

        }

Upvotes: 0

Views: 1034

Answers (2)

Kindth
Kindth

Reputation: 337

    const {currentUser} = useContext(AuthContext)

return (
 <div>
         {currentUser ? (
  <li ><NavLink to={"/"}  exact className="Nav_link" activeStyle={{ color: 'white'}} onClick={handleLogOut}>Logout </NavLink> </li>
                              ) : (
  <li ><NavLink to={"/login"} className="Nav_link" activeStyle={{ color: 'white'}}>Login </NavLink> </li>
         )}
</div>)

Upvotes: 0

Nitsan Cohen
Nitsan Cohen

Reputation: 697

You have to hold the boolean of the auth in state using useState() hook and then redirect with the !isAuth && <Redirect to="/"/> From the react-router library

Upvotes: 1

Related Questions