From d171cf1d7e5301db0364bfaeec3a099e31022c61 Mon Sep 17 00:00:00 2001 From: dertyp7 Date: Sun, 14 Jan 2024 13:03:19 +0100 Subject: [PATCH] Add hash change listener to update current section index --- src/components/SectionScroll.tsx | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/src/components/SectionScroll.tsx b/src/components/SectionScroll.tsx index f8cc7ba..7cbbb1d 100644 --- a/src/components/SectionScroll.tsx +++ b/src/components/SectionScroll.tsx @@ -1,9 +1,25 @@ -import { useState } from "react"; +import { useState, useEffect } from "react"; import "@styles/SectionScroll.scss"; export default function SectionScroll({ sections }: { sections: string[] }) { 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) { let newIndex = currentSectionIndex + direction; if (newIndex < 0) newIndex = sections.length - 1;