fix: avoid flash of page scrolling to top on refresh (#7342)

This commit is contained in:
Sébastien Lorber 2022-05-05 13:39:10 +02:00 committed by GitHub
parent 0cc4fa82c1
commit dfe743c660
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -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,
@ -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});
}