UNPKG

@boomerang-io/utils

Version:

A library of reusable utilities and hooks for React webapps on the Boomerang platform.

44 lines (38 loc) 1.28 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _react = require("react"); //Source: https://github.com/imbhargav5/rooks/blob/master/packages/shared/useMutationObserver.ts var config = { attributes: true, characterData: true, subtree: true, childList: true }; /** * * useMutationObserver hook * * Returns a mutation observer for a React Ref and fires a callback * * @param {MutableRefObject<HTMLElement | null>} ref React ref on which mutations are to be observed * @param {MutationCallback} callback Function that needs to be fired on mutation * @param {MutationObserverInit} options */ function useMutationObserver(ref, callback) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : config; (0, _react.useEffect)(function () { // Create an observer instance linked to the callback function if (ref.current) { var observer = new MutationObserver(callback); // Start observing the target node for configured mutations observer.observe(ref.current, options); return function () { observer.disconnect(); }; } }, [callback, options, ref]); } var _default = useMutationObserver; exports.default = _default;