mirror of
https://github.com/nextui-org/nextui.git
synced 2025-12-08 19:26:11 +00:00
* 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
27 lines
814 B
TypeScript
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;
|
|
}
|