Fix: mobile navigation scroll (#2486)

Co-authored-by: Samy Pessé <samypesse@gmail.com>
This commit is contained in:
Brett Jephson
2024-09-26 14:42:09 +01:00
committed by GitHub
parent 09248e0efe
commit a7066ccbe1
4 changed files with 18 additions and 7 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix scroll position when navigating pages on mobile
@@ -3,15 +3,15 @@
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import React from 'react';
import { useScrollToHash } from '@/components/hooks';
import { useScrollPage } from '@/components/hooks';
/**
* Client component to initialize interactivity for a page.
*/
export function PageClientLayout(props: {}) {
// We use this hook in the page layout to ensure the elements for the blocks
// are rendered before we scroll to the hash.
useScrollToHash();
// are rendered before we scroll to a hash or to the top of the page
useScrollPage();
useStripFallbackQueryParam();
return null;
@@ -1,4 +1,4 @@
export * from './useScrollActiveId';
export * from './useScrollToHash';
export * from './useScrollPage';
export * from './useHash';
export * from './useIsMounted';
@@ -1,12 +1,16 @@
import { usePathname } from 'next/navigation';
import React from 'react';
import { useHash } from './useHash';
/**
* Scroll to the current URL hash everytime the URL changes.
* Scroll the page to an anchor point or
* to the top of the page when navigating between pages (pathname)
* or sections of a page (hash).
*/
export function useScrollToHash() {
export function useScrollPage() {
const hash = useHash();
const pathname = usePathname();
React.useLayoutEffect(() => {
if (hash) {
const element = document.getElementById(hash);
@@ -16,6 +20,8 @@ export function useScrollToHash() {
behavior: 'smooth',
});
}
} else {
window.scrollTo(0, 0);
}
}, [hash]);
}, [hash, pathname]);
}