Home > Software engineering >  How to dynamically change URL in a Next.js application without using <Link>?
How to dynamically change URL in a Next.js application without using <Link>?

Time:11-03

I know it's possible to dynamically change the URL without refreshing the page by using <Link>; however, is it possible to do so without <Link>? For context, I'm trying to change the URL dynamically on a page to another one if a variable changes its value from false to true. The variable's value isn't dependent on a button being clicked on, so that's why I don't want to use <Link>. At the moment, I'm using window.top.location.href inside of a useEffect(), which gets the job done — but it's very clunky since the entire page reloads. Does anyone know how to achieve what I'm trying to do?

The following is what I'm currently doing:

useEffect(() => {
  if (status === true) {
    window.top.location.href='https://www.website.com'
  };
}, [status];

CodePudding user response:

I figured out a solution. All I needed to do was swap out the line with window.top.location.href to router.push(). The following is the updated code that works as intended:

useEffect(() => {
  if (status === true) {
    router.push('https://www.website.com')
  };
}, [status];

CodePudding user response:

What is the reason for wanting to change the URl without refreshing?

  • Related