Skip to content

Commit

Permalink
fix: avoid flash of page scrolling to top on refresh (#7342)
Browse files Browse the repository at this point in the history
  • Loading branch information
slorber authored May 5, 2022
1 parent 0cc4fa8 commit dfe743c
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions packages/docusaurus/src/client/ClientLifecyclesDispatcher.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,17 @@ export function dispatchLifecycleAction<K extends keyof ClientModule>(
return () => callbacks.forEach((cb) => cb?.());
}

function scrollAfterNavigation(location: Location) {
const {hash} = location;
if (!hash) {
window.scrollTo(0, 0);
} else {
const id = decodeURIComponent(hash.substring(1));
const element = document.getElementById(id);
element?.scrollIntoView();
}
}

function ClientLifecyclesDispatcher({
children,
location,
Expand All @@ -38,13 +49,8 @@ function ClientLifecyclesDispatcher({
}): JSX.Element {
useLayoutEffect(() => {
if (previousLocation !== location) {
const {hash} = location;
if (!hash) {
window.scrollTo(0, 0);
} else {
const id = decodeURIComponent(hash.substring(1));
const element = document.getElementById(id);
element?.scrollIntoView();
if (previousLocation) {
scrollAfterNavigation(location);
}
dispatchLifecycleAction('onRouteDidUpdate', {previousLocation, location});
}
Expand Down

0 comments on commit dfe743c

Please sign in to comment.