UNPKG

@utilityjs/use-on-outside-click

Version:

A React hook that invokes a callback when user clicks outside of the target element.

21 lines (20 loc) 848 B
import useGetLatest from "@utilityjs/use-get-latest"; import useEventListener from "@utilityjs/use-event-listener"; var useOnOutsideClick = function (target, callback, extendCondition) { if (extendCondition === void 0) { extendCondition = function () { return true; }; } var cachedCallback = useGetLatest(callback); useEventListener({ target: typeof window === "undefined" ? null : document, eventType: "click", handler: function (event) { var element = target && "current" in target ? target.current : target; if (element !== null && element !== event.target && !element.contains(event.target) && extendCondition(event)) { cachedCallback.current(event); } } }); }; export default useOnOutsideClick;