1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-01-20 00:08:02 +01:00
unleash.unleash/frontend/src/hooks/useOnBlur.ts

32 lines
991 B
TypeScript
Raw Normal View History

import { useEffect } from 'react';
export const useOnBlur = (
containerRef: React.RefObject<HTMLElement>,
callback: () => void
): void => {
useEffect(() => {
const handleBlur = (event: FocusEvent) => {
// setTimeout is used because activeElement might not immediately be the new focused element after a blur event
setTimeout(() => {
if (
containerRef.current &&
!containerRef.current.contains(document.activeElement)
) {
callback();
}
}, 0);
};
const containerElement = containerRef.current;
if (containerElement) {
containerElement.addEventListener('blur', handleBlur, true);
}
return () => {
if (containerElement) {
containerElement.removeEventListener('blur', handleBlur, true);
}
};
}, [containerRef, callback]);
};