Skip to content

Commit ed9de3c

Browse files
authored
refactor: rewrite useOutsideClick in typescript (#18990)
1 parent 00d8b2f commit ed9de3c

File tree

1 file changed

+17
-8
lines changed

1 file changed

+17
-8
lines changed
Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,39 @@
11
/**
2-
* Copyright IBM Corp. 2016, 2023
2+
* Copyright IBM Corp. 2016, 2025
33
*
44
* This source code is licensed under the Apache-2.0 license found in the
55
* LICENSE file in the root directory of this source tree.
66
*/
77

8-
import { useEffect, useRef } from 'react';
9-
import { useEvent } from './useEvent';
8+
import { useEffect, useRef, type RefObject } from 'react';
109
import { canUseDOM } from './environment';
10+
import { useWindowEvent } from './useEvent';
1111

12-
export function useOutsideClick(ref, callback) {
12+
export const useOutsideClick = <T extends HTMLElement>(
13+
ref: RefObject<T>,
14+
callback: (event: MouseEvent) => void
15+
) => {
1316
const savedCallback = useRef(callback);
1417

1518
useEffect(() => {
1619
savedCallback.current = callback;
17-
});
20+
}, [callback]);
1821

1922
// We conditionally guard the `useEvent` hook for SSR. `canUseDOM` can be
2023
// treated as a constant as it will be false when executed in a Node.js
2124
// environment and true when executed in the browser
2225
if (canUseDOM) {
2326
// eslint-disable-next-line react-hooks/rules-of-hooks
24-
useEvent(window, 'click', (event) => {
25-
if (ref.current && !ref.current.contains(event.target)) {
27+
useWindowEvent('click', (event) => {
28+
const { target } = event;
29+
30+
if (
31+
target instanceof Node &&
32+
ref.current &&
33+
!ref.current.contains(target)
34+
) {
2635
savedCallback.current(event);
2736
}
2837
});
2938
}
30-
}
39+
};

0 commit comments

Comments
 (0)