@carbon/react
Version:
React components for the Carbon Design System
31 lines (29 loc) • 938 B
JavaScript
/**
* Copyright IBM Corp. 2016, 2026
*
* 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 { useWindowEvent } from "./useEvent.js";
import { canUseDOM } from "./environment.js";
import { useEffect, useRef } from "react";
//#region src/internal/useOutsideClick.ts
/**
* Copyright IBM Corp. 2016, 2026
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
const useOutsideClick = (ref, callback) => {
const savedCallback = useRef(callback);
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useWindowEvent("click", (event) => {
if (!canUseDOM) return;
const { target } = event;
if (target instanceof Node && ref.current && !ref.current.contains(target)) savedCallback.current(event);
});
};
//#endregion
export { useOutsideClick };