javascriptreactjsreact-router

In react-router-dom navigate, how do I set the history for my browser's back button?


I'm using Navigate from react-router-dom.

I have a page1 that automatically redirects to login like this:

 //Code on page1
        <Navigate
            to={{
                pathname: "/login",
                state: {
                    // sets the location a user was about to access before being redirected to login
                    from: location.pathname,
                },
            }}
        />

When I click the back button on login, i stay on the login page because page1 redirects to login. How do I go two pages back such that Home->page1->login and pressing back from login goes to Home?


Solution

  • Use a redirect, e.g. a REPLACE action, to redirect to your login path instead of a regular forward, e.g. a PUSH action, action. Keep in mind also that the state is no longer a property on the To object, it is its own prop.

    Example:

    <Navigate
      to="/login"
      state={{ from: location.pathname }}
      replace
    />
    

    From here any back navigation actions will go back to the page the user was on prior to being navigated to the log-in page.

    For completeness' sake, the log-in page should also redirect back to the original route path the user was trying to accesses before they were redirected.

    Example:

    const { state } = useLocation();
    const navigate = useNavigate();
    
    ...
    
    navigate(state?.from || "/", { replace: true });