mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-28 00:50:56 +00:00
31 lines
892 B
TypeScript
31 lines
892 B
TypeScript
import { useEffect } from "react";
|
|
import { useLocation } from "react-router-dom";
|
|
|
|
/**
|
|
* Scroll to the element whose `id` matches the URL hash. Retries for a short
|
|
* window so it still lands on sections that mount after an async fetch (there is
|
|
* no router-level hash handling). Deep-link targets give a card an `id`.
|
|
*/
|
|
export function useScrollToHash(): void {
|
|
const { hash } = useLocation();
|
|
|
|
useEffect(() => {
|
|
if (!hash) return;
|
|
const id = decodeURIComponent(hash.slice(1));
|
|
let tries = 0;
|
|
let timer: ReturnType<typeof setTimeout>;
|
|
|
|
const tick = () => {
|
|
const el = document.getElementById(id);
|
|
if (el) {
|
|
el.scrollIntoView({ behavior: "smooth", block: "start" });
|
|
return;
|
|
}
|
|
if (tries++ < 20) timer = setTimeout(tick, 100);
|
|
};
|
|
|
|
timer = setTimeout(tick, 100);
|
|
return () => clearTimeout(timer);
|
|
}, [hash]);
|
|
}
|