0

When I am doing this:

navigate(
  `${window.location.pathname}?query=${encodeURIComponent(
    JSON.stringify(q)
  )}`,
  { replace: true }
);

If I scroll down a little from the page, then change a <Select /> input value, which triggers an update to this query in the URL, react-router-dom is scrolling the page to the top. When I remove this navigate code and change the select inputs, no jumping to the page top occurs, so it must be react-router-dom somehow. How do I disable or prevent this "jump to page top" behavior in react-router-dom?

Alien
  • 944
  • 2
  • 8
  • 22
  • Do you use code like `window.scrollTo(0, 0);` in a place of your code? – masoud Apr 29 '22 at 19:18
  • Does this answer your question? [react-router: How do I update the url without causing a navigation/reload?](https://stackoverflow.com/questions/57101831/react-router-how-do-i-update-the-url-without-causing-a-navigation-reload) – Andrew Hulterstrom Apr 29 '22 at 19:27
  • Why are you not using the [`useSearchParams`](https://reactrouter.com/docs/en/v6/api#usesearchparams) hook to update the `query` queryString parameter value? Can you also update your question to include/provide a [minimal, complete, and reproducible code example](https://stackoverflow.com/help/minimal-reproducible-example)? – Drew Reese Apr 29 '22 at 19:46
  • I don't know what could be causing it, but don't think I am using `window.scrollTo` anywhere. I tried switching to `useSearchParams` but didn't fix it. The linked question doesn't answer it either. I can't produce a working example, this is part of a huge app. – Alien Apr 29 '22 at 20:05
  • Ah yes actually, it appears somewhere else deep in the app we are doing `scrollTo(0, 0)` on navigation change. How can I only do it on path change not query param change? – Alien Apr 29 '22 at 20:07
  • I just did a double check that only the path changed, not the search params. Thanks for the tips! – Alien Apr 29 '22 at 20:21
  • The URL queryString (search) isn't part of the URL path and isn't considered when route path matching. It will be part of any `location` object that changes, so if the `scrollTo` logic isn't looking specifically at the `pathname` value changing it could perhaps be indirectly triggering the scrolling action. – Drew Reese Apr 29 '22 at 20:57

0 Answers0