Skip to content

feat(router-core): allow disabling scroll restoration for specific containers #4059

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions docs/router/framework/react/guide/scroll-restoration.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,35 @@ Sometimes you may want to prevent scroll restoration from happening. To do this

When `resetScroll` is set to `false`, the scroll position for the next navigation will not be restored (if navigating to an existing history event in the stack) or reset to the top (if it's a new history event in the stack).

### Disabling Scroll Restoration for specific scrollable containers

If you want to disable scroll restoration only for specific scrollable containers, you can use the `data-scroll-restoration-disable` DOM attribute:

[//]: # 'DisableRestorationExample'

```tsx
function Component() {
return (
<div
data-scroll-restoration-disable
style={{
height: '200px',
overflowY: 'scroll',
border: '1px solid red',
}}
>
<div
style={{
height: '1000px',
}}
>
Scroll me!
</div>
</div>
)
}
```

## Manual Scroll Restoration

Most of the time, you won't need to do anything special to get scroll restoration to work. However, there are some cases where you may need to manually control scroll restoration. The most common example is **virtualized lists**.
Expand Down
7 changes: 7 additions & 0 deletions packages/router-core/src/scroll-restoration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,13 @@ export function setupScrollRestoration(router: AnyRouter, force?: boolean) {
if (event.target === document || event.target === window) {
elementSelector = 'window'
} else {
const disable = (event.target as Element).hasAttribute(
'data-scroll-restoration-disable',
)
if (disable) {
return
}

const attrId = (event.target as Element).getAttribute(
'data-scroll-restoration-id',
)
Expand Down