mirror of
https://github.com/Unleash/unleash.git
synced 2025-01-20 00:08:02 +01:00
32 lines
991 B
TypeScript
32 lines
991 B
TypeScript
|
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]);
|
||
|
};
|