@carbon/react
Version:
React components for the Carbon Design System
38 lines (33 loc) • 1.11 kB
JavaScript
/**
* Copyright IBM Corp. 2016, 2023
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import { useRef, useEffect } from 'react';
import { canUseDOM } from './environment.js';
import { useWindowEvent } from './useEvent.js';
const useOutsideClick = (ref, callback) => {
const savedCallback = useRef(callback);
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// We conditionally guard the `useEvent` hook for SSR. `canUseDOM` can be
// treated as a constant as it will be false when executed in a Node.js
// environment and true when executed in the browser
if (canUseDOM) {
// TODO: https://github.com/carbon-design-system/carbon/issues/19005
/*
// eslint-disable-next-line react-hooks/rules-of-hooks
*/
useWindowEvent('click', event => {
const {
target
} = event;
if (target instanceof Node && ref.current && !ref.current.contains(target)) {
savedCallback.current(event);
}
});
}
};
export { useOutsideClick };