20 lines
742 B
JavaScript
20 lines
742 B
JavaScript
import { useEffect } from "react";
|
|
|
|
/**
|
|
* Вызывает callback при клике вне элемента, на который повешен ref.
|
|
* @param {React.RefObject} ref
|
|
* @param {Function} onOutsideClick
|
|
* @param {boolean} enabled — можно временно отключать слушатель
|
|
*/
|
|
export function useClickOutside(ref, onOutsideClick, enabled = true) {
|
|
useEffect(() => {
|
|
if (!enabled) return;
|
|
const handleClick = (e) => {
|
|
if (ref.current && !ref.current.contains(e.target)) {
|
|
onOutsideClick();
|
|
}
|
|
};
|
|
document.addEventListener("mousedown", handleClick);
|
|
return () => document.removeEventListener("mousedown", handleClick);
|
|
}, [ref, onOutsideClick, enabled]);
|
|
} |