Add hash change listener to update current section index

This commit is contained in:
dertyp7
2024-01-14 13:03:19 +01:00
parent 1607c136d8
commit d171cf1d7e

View File

@@ -1,9 +1,25 @@
import { useState } from "react"; import { useState, useEffect } from "react";
import "@styles/SectionScroll.scss"; import "@styles/SectionScroll.scss";
export default function SectionScroll({ sections }: { sections: string[] }) { export default function SectionScroll({ sections }: { sections: string[] }) {
const [currentSectionIndex, setCurrentSectionIndex] = useState(0); const [currentSectionIndex, setCurrentSectionIndex] = useState(0);
useEffect(() => {
const hash = window.location.hash.substring(1);
const index = sections.indexOf(hash);
if (index !== -1) {
setCurrentSectionIndex(index);
}
}, []);
window.onhashchange = () => {
const hash = window.location.hash.substring(1);
const index = sections.indexOf(hash);
if (index !== -1) {
setCurrentSectionIndex(index);
}
};
function scrollTo(direction: number) { function scrollTo(direction: number) {
let newIndex = currentSectionIndex + direction; let newIndex = currentSectionIndex + direction;
if (newIndex < 0) newIndex = sections.length - 1; if (newIndex < 0) newIndex = sections.length - 1;