nextui/apps/docs/hooks/use-scroll-spy.ts
WK 8c2613713a
refactor: migrate eslint to v9 (#5267)
* refactor: migrate eslint to v9

* chore: lint

* chore: update eslint command

* chore: fix lint warnings

* chore: separate lint and lint:fix

* chore: exclude contentlayer generated code

* fix(scripts): add missing await
2025-06-01 13:51:30 -03:00

27 lines
814 B
TypeScript

import * as React from "react";
export function useScrollSpy(selectors: string[], options?: IntersectionObserverInit) {
const [activeId, setActiveId] = React.useState<string | null>();
const observer = React.useRef<IntersectionObserver>();
React.useEffect(() => {
const elements = selectors.map((selector) => document.querySelector(selector));
if (observer.current) {
observer.current.disconnect();
}
observer.current = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry?.isIntersecting) {
setActiveId(entry.target.getAttribute("id"));
}
});
}, options);
elements.forEach((el) => el && observer.current?.observe(el));
return () => observer.current?.disconnect();
}, [selectors]);
return activeId;
}