@carbon/react
Version:
React components for the Carbon Design System
37 lines (31 loc) • 1.07 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.
*/
;
var React = require('react');
var environment = require('./environment.js');
var useEvent = require('./useEvent.js');
const useOutsideClick = (ref, callback) => {
const savedCallback = React.useRef(callback);
React.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 (environment.canUseDOM) {
// eslint-disable-next-line react-hooks/rules-of-hooks
useEvent.useWindowEvent('click', event => {
const {
target
} = event;
if (target instanceof Node && ref.current && !ref.current.contains(target)) {
savedCallback.current(event);
}
});
}
};
exports.useOutsideClick = useOutsideClick;