Files
mostlymatter/webapp/platform/components/src/common/hooks/useClickOutsideRef.ts
Harrison Healey 4d03becdd1 MM-52624/MM-57094 Update ESLint and our ESLint plugin (#26398)
* Update ESLint and plugins

* Move most channels-specific ESLint configuration into ESLint plugin

* Add ESLint to types and client packages

* Add ESLint to components package
2024-03-13 22:07:28 +00:00

25 строки
861 B
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import type {MutableRefObject} from 'react';
import {useEffect} from 'react';
export function useClickOutsideRef(ref: MutableRefObject<HTMLElement | null>, handler: (event: MouseEvent) => void): void {
useEffect(() => {
function onMouseDown(event: MouseEvent) {
const target = event.target as any;
if (ref.current && target instanceof Node && !ref.current.contains(target)) {
handler(event);
}
}
// Bind the event listener
document.addEventListener('mousedown', onMouseDown);
return () => {
// Unbind the event listener on clean up
document.removeEventListener('mousedown', onMouseDown);
};
}, [ref, handler]);
}