Skip to content

Commit 0f59908

Browse files
committed
add fix for layout shift on anchors
1 parent bbd1905 commit 0f59908

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

src/hooks/useAnchorFix.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import { useEffect } from 'react';
2+
3+
// We use some components only on the client side, but because Docusaurus is a
4+
// static site generator, there is a weird bug where if you click on a link to
5+
// an anchor, the page will load at the correct location and then jump to the wrong
6+
// place after a few moments as the client side components load in and shift the
7+
// page layout. This is a hack to fix this bug.
8+
export function useAnchorFix() {
9+
useEffect(() => {
10+
const handleAnchorScroll = () => {
11+
const hash = window.location.hash;
12+
if (hash) {
13+
// Wait for content to load, then scroll
14+
setTimeout(() => {
15+
const element = document.querySelector(hash);
16+
if (element) {
17+
element.scrollIntoView({ behavior: 'smooth' });
18+
}
19+
}, 500); // Adjust timing as needed
20+
}
21+
};
22+
23+
// Run on route changes
24+
handleAnchorScroll();
25+
26+
// Also run when images/content finish loading
27+
window.addEventListener('load', handleAnchorScroll);
28+
29+
return () => {
30+
window.removeEventListener('load', handleAnchorScroll);
31+
};
32+
}, []);
33+
}

src/theme/DocRoot/Layout/index.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@ import BackToTopButton from '@theme/BackToTopButton';
55
import DocPageLayoutSidebar from '@theme/DocRoot/Layout/Sidebar';
66
import DocPageLayoutMain from '@theme/DocRoot/Layout/Main';
77
import styles from './styles.module.css';
8+
import { useAnchorFix } from '../../hooks/useAnchorFix';
89
export default function DocPageLayout({children}) {
10+
useAnchorFix(); // fix for layout shifts which occur when navigating to an anchor
911
const sidebar = useDocsSidebar();
1012
const [hiddenSidebarContainer, setHiddenSidebarContainer] = useState(false);
1113
return (

0 commit comments

Comments
 (0)