Loading...
Please waitLoading...
Please waitpnpm dlx uselab@latest add use-mutation-observer
import * as React from "react"
import { useMutationObserver } from "@/hooks/use-mutation-observer"
export function Component() {
const ref = React.useRef<HTMLDivElement>(null)
const callback: MutationCallback = (mutationsList) => {
for (const mutation of mutationsList) {
if (mutation.type === "attributes") {
console.log("Attribute changed:", mutation.attributeName)
} else if (mutation.type === "childList") {
console.log("Child nodes changed")
} else if (mutation.type === "characterData") {
console.log("Text content changed")
}
}
}
useMutationObserver(ref, callback)
return (
<div ref={ref}>
<p>Observe changes in this element</p>
</div>
)
}| Name | Type | Description | Default Value | Optional |
|---|---|---|---|---|
ref | React.MutableRefObject<HTMLElement | null> | A ref to the DOM element to observe. | - | No |
callback | MutationCallback | A callback function that will be called when mutations are observed. | - | No |
options | MutationObserverInit | Options for the MutationObserver (e.g., attributes, childList, etc.). | { attributes: true, characterData: true, childList: true, subtree: true } | Yes |