petyosi / react-virtuoso

The most powerful virtual list component for React
https://virtuoso.dev
MIT License
5.16k stars 299 forks source link

While scrolling down, automatically scrollbar is jumping to the top. #1014

Closed mohan1140bhonu closed 9 months ago

mohan1140bhonu commented 9 months ago

Describe the bug While scrolling the items from virtuoso, automatically scrollbar is jumping to top after 3 to 4 scroll attempts. This is happening after using the useWindowScroll. without this key scrollbar was not jumping. But to avoid duel scrollbar i need to use this keyword.

Reproduction I cant share the code since it was a production code.

To Reproduce Steps to reproduce the behavior:

Expected behavior While scrolling down, it should not jump back to the top of the page.

Screenshots If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

Additional context Add any other context about the problem here.

petyosi commented 9 months ago

If you can't share a proper reproduction, then you can sponsor the project with an adequate amount and contact me over email - I will examine your setup and advise you accordingly.

MartinDawson commented 3 months ago

For me, this is happening when I use the page from the url query params. Interestingly it ONLY happened on useWindowScroll, the reason this is, is because my navigate() function (from redwoodjs) is internally doing this:

window.scrollTo(0,0).

  const urlParams = new URLSearchParams(location.search)
  const page = parseInt(urlParams.get('page') ?? '0', 10)

  const handleLoadMore = useCallback(() => {
    const nextPage = page + 1

    // Offending line
    navigate(`?page=${nextPage}`)
  }, [page])

So make sure you aren't calling any router stuff that is internally resetting the scroll position if you want to sync with your queryParams. The solution is this:

  const handleLoadMore = useCallback(() => {
    const nextPage = page + 1

    setPage(nextPage)

    const url = new URL(window.location.toString())

    url.searchParams.set('page', nextPage.toString())

    window.history.replaceState({}, '', url)
  }, [page])

Thanks for this great library btw, it really is outstanding.