Fixing root element for mutation observer

Signed-off-by: Alex Andreev <alex.andreev.email@gmail.com>
This commit is contained in:
Alex Andreev committed 2021-03-09 18:56:54 +03:00
1 parent 7d1f356d88
commit 31fd3a351e
2 files changed
+11 -6

No files matched your search

@@ -20,8 +20,12 @@ export function ScrollSpy(props: Props) {
}
};
const getSectionsParentElement = () => {
return sections.current?.[0].parentElement;
};
const updateNavigation = () => {
setTree(getNavigation(sections.current[0].parentElement));
setTree(getNavigation(getSectionsParentElement()));
};
const getNavigation = (element: Element) => {
@@ -82,7 +86,7 @@ export function ScrollSpy(props: Props) {
updateNavigation();
}, [activeElementId]);
useMutationObserver(parent, updateNavigation);
useMutationObserver(getSectionsParentElement(), updateNavigation);
return (
<div className="ScrollSpy" ref={parent}>
+5 -4
View File
@@ -1,4 +1,4 @@
import { MutableRefObject, useEffect } from "react";
import { useEffect } from "react";
const config: MutationObserverInit = {
subtree: true,
@@ -8,15 +8,16 @@ const config: MutationObserverInit = {
};
export function useMutationObserver(
ref: MutableRefObject<HTMLElement>,
root: Element,
callback: MutationCallback,
options: MutationObserverInit = config
) {
useEffect(() => {
if (ref.current) {
if (root) {
const observer = new MutationObserver(callback);
observer.observe(ref.current, options);
observer.observe(root, options);
return () => {
observer.disconnect();