Search code examples
javascriptreactjshyperlinkjsxreact-router-dom

How do I use <Link> to perform an action similar to " window.location = "/GameOverDied"; " in JS React?


Currently I am trying to do some animation transitions with a game I'm building in React and I don't want the re-render/refresh function of href or window.location. How would I use <Link> from react-router-dom handled in this regard?

const handleGameOver = () => {
  if (health < 1) {
    window.location = "/GameOverDied";
  } else if (fuel < 1) {
    window.location = "/GameOverFuel";
  } else {
  }
};

I haven't tried anything yet because I'm not getting the answers I was looking for anywhere else.


Solution

  • Link is a React component and would need to be rendered to have any effect in the UI as a declarative navigation action. Use the useNavigate hook instead to issue an imperative navigation action from a callback.

    Example:

    import { useNavigate } from 'react-router-dom';
    
    ...
    
    const navigate = useNavigate();
    
    ...
    
    const handleGameOver = () => {
      if (health < 1) {
        navigate("/GameOverDied", { replace: true });
      } else if (fuel < 1) {
        navigate("/GameOverFuel", { replace: true });
      } else {
      }
    };
    
    ...