Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 {
  }
};

...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading