2023-09-05 15:31:31 +02:00
|
|
|
import { useEffect } from 'react';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Hook to handle outside clicks for a given list of refs.
|
|
|
|
*
|
|
|
|
* @param {Array<React.RefObject>} refs - List of refs to the target elements.
|
|
|
|
* @param {Function} callback - Callback to execute on outside click.
|
|
|
|
*/
|
|
|
|
export const useOnClickOutside = (
|
|
|
|
refs: Array<React.RefObject<HTMLElement>>,
|
2023-10-02 14:25:46 +02:00
|
|
|
callback: Function,
|
2023-09-05 15:31:31 +02:00
|
|
|
) => {
|
|
|
|
useEffect(() => {
|
|
|
|
const handleClickOutside = (event: MouseEvent) => {
|
|
|
|
// Check if event target is outside all provided refs
|
|
|
|
if (
|
2023-10-02 14:25:46 +02:00
|
|
|
!refs.some((ref) => ref.current?.contains(event.target as Node))
|
2023-09-05 15:31:31 +02:00
|
|
|
) {
|
|
|
|
callback();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
document.addEventListener('click', handleClickOutside);
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
document.removeEventListener('click', handleClickOutside);
|
|
|
|
};
|
|
|
|
}, [refs, callback]);
|
|
|
|
};
|