Skip to content

Commit 477dbcf

Browse files
committed
feat: scroll to top when pathname is changing
1 parent 0fe0eb2 commit 477dbcf

File tree

3 files changed

+66
-31
lines changed

3 files changed

+66
-31
lines changed

package-lock.json

Lines changed: 30 additions & 22 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@
4747
"@radix-ui/react-switch": "^1.0.3",
4848
"@radix-ui/react-toggle": "^1.1.0",
4949
"@radix-ui/react-tooltip": "^1.0.7",
50-
"@tanstack/react-router": "^1.29.2",
50+
"@tanstack/react-router": "^1.46.4",
5151
"axios": "^1.6.8",
5252
"axios-retry": "^4.1.0",
5353
"chroma-js": "^2.4.2",

src/routes/__root.tsx

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,40 @@
1-
import { createRootRoute, Outlet } from '@tanstack/react-router'
1+
import {
2+
createRootRoute,
3+
Outlet,
4+
useLocation,
5+
} from '@tanstack/react-router'
6+
import { useEffect, useRef } from 'react'
27

38
import { MainLayout } from '../layouts/main'
49

510
export const Route = createRootRoute({
6-
component: () => (
7-
<>
8-
<MainLayout>
9-
<Outlet />
10-
</MainLayout>
11-
</>
12-
),
11+
component: () => {
12+
useScrollToTop()
13+
14+
return (
15+
<>
16+
<MainLayout>
17+
<Outlet />
18+
</MainLayout>
19+
</>
20+
)
21+
},
1322
})
23+
24+
function useScrollToTop() {
25+
const $main = useRef<HTMLElement | null>(null)
26+
const pathname = useLocation({
27+
select: (location) => location.pathname,
28+
})
29+
30+
useEffect(() => {
31+
if (!$main.current) {
32+
$main.current = document.querySelector('main')
33+
}
34+
35+
$main.current?.scroll({
36+
behavior: 'instant',
37+
top: 0,
38+
})
39+
}, [pathname])
40+
}

0 commit comments

Comments
 (0)