From dfe743c66056e217f5de8e4c7cec22620739f0bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Lorber?= Date: Thu, 5 May 2022 13:39:10 +0200 Subject: [PATCH] fix: avoid flash of page scrolling to top on refresh (#7342) --- .../src/client/ClientLifecyclesDispatcher.tsx | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/packages/docusaurus/src/client/ClientLifecyclesDispatcher.tsx b/packages/docusaurus/src/client/ClientLifecyclesDispatcher.tsx index 7c797af092d7..caf75a1647bf 100644 --- a/packages/docusaurus/src/client/ClientLifecyclesDispatcher.tsx +++ b/packages/docusaurus/src/client/ClientLifecyclesDispatcher.tsx @@ -27,6 +27,17 @@ export function dispatchLifecycleAction( 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, @@ -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}); }