Skip to content

Commit a7066cc

Browse files
Fix: mobile navigation scroll (#2486)
Co-authored-by: Samy Pessé <samypesse@gmail.com>
1 parent 09248e0 commit a7066cc

File tree

4 files changed

+18
-7
lines changed

4 files changed

+18
-7
lines changed

.changeset/blue-wasps-sparkle.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'gitbook': patch
3+
---
4+
5+
Fix scroll position when navigating pages on mobile

packages/gitbook/src/app/(space)/(content)/[[...pathname]]/PageClientLayout.tsx

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,15 @@
33
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
44
import React from 'react';
55

6-
import { useScrollToHash } from '@/components/hooks';
6+
import { useScrollPage } from '@/components/hooks';
77

88
/**
99
* Client component to initialize interactivity for a page.
1010
*/
1111
export function PageClientLayout(props: {}) {
1212
// We use this hook in the page layout to ensure the elements for the blocks
13-
// are rendered before we scroll to the hash.
14-
useScrollToHash();
13+
// are rendered before we scroll to a hash or to the top of the page
14+
useScrollPage();
1515

1616
useStripFallbackQueryParam();
1717
return null;
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
export * from './useScrollActiveId';
2-
export * from './useScrollToHash';
2+
export * from './useScrollPage';
33
export * from './useHash';
44
export * from './useIsMounted';
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,16 @@
1+
import { usePathname } from 'next/navigation';
12
import React from 'react';
23

34
import { useHash } from './useHash';
45

56
/**
6-
* Scroll to the current URL hash everytime the URL changes.
7+
* Scroll the page to an anchor point or
8+
* to the top of the page when navigating between pages (pathname)
9+
* or sections of a page (hash).
710
*/
8-
export function useScrollToHash() {
11+
export function useScrollPage() {
912
const hash = useHash();
13+
const pathname = usePathname();
1014
React.useLayoutEffect(() => {
1115
if (hash) {
1216
const element = document.getElementById(hash);
@@ -16,6 +20,8 @@ export function useScrollToHash() {
1620
behavior: 'smooth',
1721
});
1822
}
23+
} else {
24+
window.scrollTo(0, 0);
1925
}
20-
}, [hash]);
26+
}, [hash, pathname]);
2127
}

0 commit comments

Comments
 (0)