@react-md/utils
Version:
General utils for react-md.
45 lines • 1.52 kB
JavaScript
import { useEffect } from "react";
import { containsElement } from "./containsElement";
/**
* Gets the HTMLElement or null from a provided RefObject or HTMLElement/null
* @internal
*/
export function getElement(element) {
if (!element) {
return null;
}
if (typeof element.current !== "undefined") {
return element.current;
}
return element;
}
/**
* Triggers a callback function when another element in the page is clicked that
* is outside of the provided element. This is generally used for closing
* temporary elements when something else within the page has been clicked.
*
* The callback will be provided the current `element` as well as the click
* target if additional logic should be applied before closing.
*
* @typeParam E - The type of element
*/
export function useCloseOnOutsideClick(_a) {
var enabled = _a.enabled, element = _a.element, onOutsideClick = _a.onOutsideClick;
useEffect(function () {
if (!enabled) {
return;
}
function handleClick(event) {
var target = event.target;
var el = getElement(element);
if (!containsElement(el, target)) {
onOutsideClick(el, target, containsElement);
}
}
window.addEventListener("click", handleClick);
return function () {
window.removeEventListener("click", handleClick);
};
}, [enabled, element, onOutsideClick]);
}
//# sourceMappingURL=useCloseOnOutsideClick.js.map