1
0
mirror of https://github.com/lensapp/lens.git synced 2025-05-20 05:10:56 +00:00

Fixing root element for mutation observer

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

View File

@ -20,8 +20,12 @@ export function ScrollSpy(props: Props) {
} }
}; };
const getSectionsParentElement = () => {
return sections.current?.[0].parentElement;
};
const updateNavigation = () => { const updateNavigation = () => {
setTree(getNavigation(sections.current[0].parentElement)); setTree(getNavigation(getSectionsParentElement()));
}; };
const getNavigation = (element: Element) => { const getNavigation = (element: Element) => {
@ -82,7 +86,7 @@ export function ScrollSpy(props: Props) {
updateNavigation(); updateNavigation();
}, [activeElementId]); }, [activeElementId]);
useMutationObserver(parent, updateNavigation); useMutationObserver(getSectionsParentElement(), updateNavigation);
return ( return (
<div className="ScrollSpy" ref={parent}> <div className="ScrollSpy" ref={parent}>

View File

@ -1,4 +1,4 @@
import { MutableRefObject, useEffect } from "react"; import { useEffect } from "react";
const config: MutationObserverInit = { const config: MutationObserverInit = {
subtree: true, subtree: true,
@ -8,15 +8,16 @@ const config: MutationObserverInit = {
}; };
export function useMutationObserver( export function useMutationObserver(
ref: MutableRefObject<HTMLElement>, root: Element,
callback: MutationCallback, callback: MutationCallback,
options: MutationObserverInit = config options: MutationObserverInit = config
) { ) {
useEffect(() => { useEffect(() => {
if (ref.current) { if (root) {
const observer = new MutationObserver(callback); const observer = new MutationObserver(callback);
observer.observe(ref.current, options); observer.observe(root, options);
return () => { return () => {
observer.disconnect(); observer.disconnect();