@boomerang-io/utils
Version:
A library of reusable utilities and hooks for React webapps on the Boomerang platform.
42 lines (38 loc) • 1.25 kB
JavaScript
;
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
const 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) {
let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : config;
(0, _react.useEffect)(() => {
// Create an observer instance linked to the callback function
if (ref.current) {
const observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(ref.current, options);
return () => {
observer.disconnect();
};
}
}, [callback, options, ref]);
}
var _default = exports.default = useMutationObserver;