TanStackT
TanStack14mo ago
36 replies
hidden-sapphire

Implementing a Table of Contents (hash change scroll issue)

I am trying to implement a Table of Contents sidebar for an API documentation site (in one-page style) that contains hash links (e.g., to="#Auth"). When clicking on one of the Table of Contents links, having the browser scroll down to the anchor that matches the hash is working as expected. The part I'm running into some trouble with is when I try to update the hash as a result of the user scrolling down the content part of the site. When I try to update the hash in the URL, the browser scrolls to the anchor element, but I'd really like to avoid that behavior so the user can scroll at their own pace. I've tried using navigate, updating the location state using router.buildAndCommitLocation, and even just trying window.location.hash = '#Auth'. All of these result in the hash being updated in the address bar, but they also all take over scrolling. I believe the latter is happening because the history implementation is overwriting window.history to support the router's subscriptions.

I found this PR, which seems relevant to the issue I'm experiencing: https://github.com/TanStack/router/pull/1105#issuecomment-2019026150 (the code causing the scrolling seems to have moved here: https://github.com/TanStack/router/blob/35af575ab4c623556ecdb613ac1c85864f0c95d9/packages/react-router/src/Transitioner.tsx#L146)

If I'm understanding correctly, the recommendation was to try using the Scroll Restoration API. I wasn't able to get that to work either, unfortunately.

Here's a StackBlitz that hopefully minimally demonstrates the issue: https://stackblitz.com/edit/tanstack-router-785cuome?file=src%2Fmain.tsx I also tried using useElementScrollRestoration, but it didn't solve the issue either. (The intersection observer implementation here isn't without issue, but it should be fine to demonstrate the routing problem I have, I think).

Has anyone found a solution for something like this? Thanks!
Was this page helpful?