Go back

Preventing the default scroll event with Next.js useRouter

I've been working on year-in-review — an archive of articles that features the EOY review of folks in the tech community — with a couple of awesome devs for a while now. I remember opening an issue when I encountered an error that had to do with the browser scrolling back to the top of the page when any of the filter buttons are clicked.

At first, my approach to fixing this was the traditional way. I relied on using the native preventDefault() function — take a look at the snippet below — LMAO! It did not do what I expected.

const handleYears = (year, e) => {
  e.preventDefault()
 
  setSelectedYear(year)
  setActiveYear(year)
  router.push({ pathname: '/', query: { year } })
}

After trying over and over again, I went ahead to open the issue, I even added the "help wanted" label to it, because, honestly I needed help at that time. I honestly thought help wasn't going to come — until Dayan Ruiz submitted a Pull Request, four hours ago, I was stunned and happy at the same time!

What I struggled with for a while, till I abandoned it, was fixed with two lines of code, as a modification to the handleYears() function. You can take a look at the snippet below. "How did I not think of this?!!"

router.push(
  {
    pathname: '/',
    query: { ...router.query, year: year },
  },
  undefined,
  { scroll: false }
)

So here's how the snippet above works:

The router.push method is from the Next.js useRouter hook, which is used to navigate to a new URL. This method accepts three arguments:

pathname: A string representing the path of the new URL. In this case, "/" is passed, which means the URL will be the root of the website.

query: An object containing query parameters to be added to the URL.

In this case, the snippet above is using the spread operator { ...router.query } to copy all of the current query parameters and then adds a new query parameter year with a value of year.

options: An object containing options for navigation. Here, { scroll: false } is passed, which disables scrolling back to the top of the page when the new URL is navigated to.

wrapping up

So, in summary, this fix fires a navigation event to the root URL of the website, with the current query parameters plus a new year parameter, and with the option to prevent scrolling back to the top of the page.

Thank you for reading and I hope this helped you.

In this article