skip to Main Content

I’m using ReactJS to develop my frontend web.

The first page with router is /route-1

In the useEffect function after the page loaded, it checks something and needs to redirect to /route-2 using navigate:

import { useNavigate } from "react-router-dom"
const navigate = useNavigate()
navigate("/route-2")

And in the 2nd page, user clicks a link to navigate to /route-3, link is described like this

import { Link } from "react-router-dom"

<Link to="/route-3" className="link">Go to route 3</Link>

Finally, user click back button in the browser, and then the page goes back to /route-1 which was not my expectation. I want to redirect to /route-2 after clicking back button in the browser.

So what do I need to do to satisfy my expectation

Thanks

2

Answers


  1. Check replace option in your useNavigate hook. It should be false.

    Ideally, as described in the docs you should use redirect. This way you’ll have more control over your re-routing.

    If you just want to get it to work. You can use the window object and handle the re-routing manually.

    Hope this helps.

    Login or Signup to reply.
  2. In your first page component (Route1Component), you can use the useEffect hook to check your condition and then use the history object to redirect to /route-2. Since you’re already using useNavigate, you can also use useHistory alongside it for more complex scenarios like this.

    First, import useHistory from react-router-dom:

    import { useHistory } from "react-router-dom";
    

    Then, inside your component, get access to the history object:

    const history = useHistory();
    

    Modify your useEffect to use history.push(‘/route-2’) instead of navigate(‘/route-2’):

    useEffect(() => {
      // Check your condition here
      if (/* your condition */) {
        history.push('/route-2');
      }
    }, []);
    

    To prevent the default back button behavior and redirect to /route-2 instead, you can listen for the popstate event on the window object and then use history.push(‘/route-2’) to redirect accordingly.

    useEffect(() => {
      const unlisten = history.listen(() => {
        // Listen for changes in the current location
      });
    
      window.addEventListener('popstate', () => {
        // Override the default back button behavior
        history.push('/route-2');
      });
    
      return () => {
        // Cleanup listener
        unlisten();
        window.removeEventListener('popstate');
      };
    }, [history]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search