Hopefully fixed the scrool to anchor when changing page
This commit is contained in:
parent
73c25fd924
commit
5fc1d26243
|
@ -1,12 +1,12 @@
|
||||||
import { useRouter } from "next/router";
|
import { useRouter } from "next/router";
|
||||||
import { useEffect } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { useBoolean, useCounter } from "usehooks-ts";
|
import { useCounter } from "usehooks-ts";
|
||||||
import { isDefined } from "helpers/others";
|
import { isDefined } from "helpers/others";
|
||||||
|
|
||||||
export const useScrollIntoView = (): void => {
|
export const useScrollIntoView = (): void => {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { count, increment } = useCounter(0);
|
const { count, increment } = useCounter(0);
|
||||||
const { value: hasReachedElem, setTrue: setHasReachedElem } = useBoolean();
|
const [hasReachedElem, setHasReachedElem] = useState(false);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!hasReachedElem) {
|
if (!hasReachedElem) {
|
||||||
const indexHash = router.asPath.indexOf("#");
|
const indexHash = router.asPath.indexOf("#");
|
||||||
|
@ -17,7 +17,7 @@ export const useScrollIntoView = (): void => {
|
||||||
if (isDefined(element)) {
|
if (isDefined(element)) {
|
||||||
console.log(`[useScrollIntoView] ${hash} found`);
|
console.log(`[useScrollIntoView] ${hash} found`);
|
||||||
element.scrollIntoView();
|
element.scrollIntoView();
|
||||||
setHasReachedElem();
|
setHasReachedElem(true);
|
||||||
} else {
|
} else {
|
||||||
console.log(`[useScrollIntoView] ${hash} not found`);
|
console.log(`[useScrollIntoView] ${hash} not found`);
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
|
@ -27,4 +27,6 @@ export const useScrollIntoView = (): void => {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, [increment, router.asPath, count, hasReachedElem, setHasReachedElem]);
|
}, [increment, router.asPath, count, hasReachedElem, setHasReachedElem]);
|
||||||
|
|
||||||
|
useEffect(() => setHasReachedElem(false), [router.asPath]);
|
||||||
};
|
};
|
||||||
|
|
Loading…
Reference in New Issue