From b727f462c600cd878387c93fd9229c48877052cb Mon Sep 17 00:00:00 2001 From: Manuel Schiller Date: Sun, 27 Apr 2025 22:09:46 +0200 Subject: [PATCH] feat: allow to disable scroll restoration for specific containers --- .../react/guide/scroll-restoration.md | 29 +++++++++++++++++++ .../router-core/src/scroll-restoration.ts | 7 +++++ 2 files changed, 36 insertions(+) diff --git a/docs/router/framework/react/guide/scroll-restoration.md b/docs/router/framework/react/guide/scroll-restoration.md index 77634d03e9..7d2917a33e 100644 --- a/docs/router/framework/react/guide/scroll-restoration.md +++ b/docs/router/framework/react/guide/scroll-restoration.md @@ -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 ( +
+
+ Scroll me! +
+
+ ) +} +``` + ## 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**. diff --git a/packages/router-core/src/scroll-restoration.ts b/packages/router-core/src/scroll-restoration.ts index 7efa94a908..94c7721385 100644 --- a/packages/router-core/src/scroll-restoration.ts +++ b/packages/router-core/src/scroll-restoration.ts @@ -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', )