outsideclick-react is a lightweight React package that detects clicks outside a specified element, useful for dropdowns, modals, etc.
npm install outsideclick-reactor
yarn add outsideclick-reactimport { useOutsideClick } from "outsideclick-react"; function MyComponent() { const handleOutsideClick = (e) => { // Handle outside click }; const ref = useOutsideClick(handleOutsideClick); /* const ref = useOutsideClick(handleOutsideClick, ".ignore-element") */ return <div ref={ref}>{/* Your component */}</div>; }import { OutsideClick } from "outsideclick-react"; function MyComponent() { return ( <OutsideClick onOutsideClick={() => { // Handle outside click }} ignoreElement=".ignore" > <div>{/* Your component */}</div> </OutsideClick> ); }A hook that detects clicks outside of a specified element.
- outsideClick:
(v: HTMLElement) => void- A function that gets called when an outside click is detected. - ignoreElement (optional):
IgnoreElementType- An element or selector that should be ignored when detecting outside clicks.
- A
refobject that should be attached to the target element.
A component that detects clicks outside of its children.
onOutsideClick: Function that is called when an outside click is detected.ignoreElement: An element or selector to ignore when detecting outside clicks.
If you'd like to contribute, please submit a pull request.
If you want to support my work, you can buy me a coffee!
