How do I go back to home page if previous path don't exists react router v6

Viewed 441

I redirect users to the login page from the checkout page if they are not authenticated. once they log in I take them back to the previous page, but I want to redirect them to the home page if they were not redirected from a page prior.

2 Answers

Add below code to your Login.jsx file in Login function. So that if there is user and already logged in and trying to go back on previous page and it is login page then it will directly redirect on home page instead of login page .

  const user = JSON.parse(localStorage.getItem("user"));
  const history = useHistory();
  useEffect(() => {
    if (user) {
      history.push("/");
    }
  });

Assuming you are forwarding a redirect target when redirecting to the login page, then you can just provide a fallback value in the login flow to your home path "/".

Example:

Simple PrivateRoutes component that forwards the current location object.

import { Navigate, Outlet } from 'react-router-dom';

const PrivateRoutes = () => {
  const location = useLocation();
  
  // auth logic

  return authenticated 
    ? <Outlet />
    : <Navigate to="/login" replace state={{ from: location }} />;
}

Login component/handler

export default function Login() {
  const location = useLocation();
  const navigate = useNavigate();
  
  // auth state

  const loginData = () => { ... };

  if (authenticated) {
    const { from } = location.state || {};
    navigate(from.pathname || "/", { replace: true });
  }

  return (
    <button type="button" onClick={loginData}>
      Login
    </button>
  );
}
Related