Skip to content
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

refactor(react-router): expose scrollBehavior on the ScrollRestoration component #3053

Merged
merged 5 commits into from
Dec 21, 2024
Merged
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
17 changes: 17 additions & 0 deletions docs/framework/react/guide/scroll-restoration.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,3 +137,20 @@ function Component() {
)
}
```

## Scroll Behavior

To control the scroll behavior when navigating between pages, you can use the `scrollBehavior` option. This allows you to make the transition between pages instant instead of a smooth scroll. The global configuration of scroll restoration behavior has the same options as those supported by the browser, which are `smooth`, `instant`, and `auto` (see [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView#behavior) for more information).

```tsx
import { ScrollRestoration } from '@tanstack/react-router'

function Root() {
return (
<>
<ScrollRestoration scrollBehavior="instant" />
<Outlet />
</>
)
}
```
7 changes: 6 additions & 1 deletion packages/react-router/src/scroll-restoration.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ const cache: Cache = sessionsStorage

export type ScrollRestorationOptions = {
getKey?: (location: ParsedLocation) => string
scrollBehavior?: ScrollToOptions['behavior']
}

/**
Expand Down Expand Up @@ -154,7 +155,11 @@ export function useScrollRestoration(options?: ScrollRestorationOptions) {
if (key === restoreKey) {
if (elementSelector === windowKey) {
windowRestored = true
window.scrollTo(entry.scrollX, entry.scrollY)
window.scrollTo({
top: entry.scrollY,
left: entry.scrollX,
behavior: options?.scrollBehavior,
})
} else if (elementSelector) {
const element = document.querySelector(elementSelector)
if (element) {
Expand Down
Loading