Skip to content

Commit

Permalink
refactor(react-router): expose scrollBehavior on the `ScrollRestora…
Browse files Browse the repository at this point in the history
…tion` component (#3053)

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Sean Cassiere <33615041+SeanCassiere@users.noreply.github.com>
  • Loading branch information
3 people authored Dec 21, 2024
1 parent e44bec8 commit 72b7c82
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
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

0 comments on commit 72b7c82

Please sign in to comment.