skip to Main Content
const navigate = useNavigate();
navigate(-1)

This is what I am trying to do. However, I want to know what the previous page is before going back. If the previous page is some other site, then of course, it should have no effect.

2

Answers


  1. You can do a check to verify the url origin using window.location.origin.

    const currentOrigin = window.location.origin;
    
    
    const navigate = useNavigate();
    currentOrigin === "https://example.com" ? navigate(-1) : null
    
    
    Login or Signup to reply.
  2. Yes, we can maintain some "state" to indicate that where it is navigated exactly from.

    For Example:

    const navigate = useNavigate();
    navigate("/newPage", { state: { fromCurrentApp: true } });
    

    So, from current page you can check that state and handle the navigation.

    import { useLocation, useNavigate } from 'react-router-dom';
    
    const { state } = useLocation();
    const navigate = useNavigate();
    
    const { fromCurrentApp } = state || {};
    if (fromCurrentApp) {
      navigate('/home', { state: { fromCurrentApp: true } });
    } else {
      navigate(-1);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search