@dnanpm/styleguide
Version:
DNA Styleguide repository provides the set of components and theme object used in various DNA projects.
35 lines (32 loc) • 1.4 kB
JavaScript
import { useEffect } from 'react';
/**
* Hook to handle the click outside the referenced element
*
* @param ref - reference to the targeted element
* @param closeWhenTagClicked - provided array of tag names in lowercase which will also close dropdown. Works if tag or first parent is clicked.
* @param callback - callback
*/
const useCloseOutsideOrElementClicked = ({ ref, closeWhenTagClicked }, callback) => {
const handleClick = (e) => {
const target = e.target;
const parent = target.parentNode;
const isElementInList = closeWhenTagClicked.some(tag => {
var _a, _b, _c;
if (!target.parentNode) {
return tag === ((_a = target.tagName) === null || _a === void 0 ? void 0 : _a.toLowerCase());
}
return tag === ((_b = target.tagName) === null || _b === void 0 ? void 0 : _b.toLowerCase()) || tag === ((_c = parent.tagName) === null || _c === void 0 ? void 0 : _c.toLowerCase());
});
if ((ref.current && !ref.current.contains(target)) ||
(isElementInList && !target.dataset.noClose)) {
callback();
}
};
useEffect(() => {
document.addEventListener('click', handleClick);
return () => {
document.removeEventListener('click', handleClick);
};
});
};
export { useCloseOutsideOrElementClicked as default };