A lightweight React hook that returns a ref and triggers a callback when clicks occur outside the referenced element. Supports stopPropagation to prevent outside clicks when needed.
npm install @junaidakbar076/react-outside-click-handlerA lightweight React hook that returns a ref and triggers a callback when clicks occur outside the referenced element. Perfect for modals, dropdowns, tooltips, and popovers.
stopPropagation for preventing outside clicks when needed``bash`
npm install @junaidakbar076/react-outside-click-handler
or with yarn:
`bash`
yarn add @junaidakbar076/react-outside-click-handler
`tsx
import React, { useState } from "react";
import { useOutsideClickHandler } from "@junaidakbar076/react-outside-click-handler";
function App() {
const [open, setOpen] = useState(true);
const ref = useOutsideClickHandler
setOpen(false);
});
return (
π Prevent Outside Clicks with
stopPropagationIf you want to stop the outside click handler from firing when clicking inside your component,
you can call
event.stopPropagation() inside your own handler.$3
`tsx
import { useOutsideClickHandler } from "@junaidakbar076/react-outside-click-handler";function App() {
const ref = useOutsideClickHandler((event) => {
alert("Outside clicked!");
});
return (
onClick={(e) => {
e.stopPropagation(); // β prevents outside click handler
alert("Inside button clicked");
}}
>
Inside Button
);
}
`
$3
When you add a button to reopen the component, make sure to call
e.stopPropagation() inside its onClick.
This prevents the click event from bubbling up and being caught as an outside click.`tsx
onClick={(e) => {
e.stopPropagation(); // β prevents immediate outside click trigger
setOpen(true);
}}
>
Reopen Box
`
$3
The hook listens for
click events on the whole document.
If you want to prevent the outside click handler from running, you can call e.stopPropagation() on any elementβs click event β whether inside or outside the component ref.This is useful when:
- You have buttons inside the component that should not trigger outside closing.
- You have controls outside the component (like a βReopenβ button) that should not be treated as an outside click.
`tsx
import React, { useState } from "react";
import { useOutsideClickHandler } from "@junaidakbar076/react-outside-click-handler";const Example = () => {
const [open, setOpen] = useState(true);
const ref = useOutsideClickHandler(() => setOpen(false));
return (
{open ? (
Click outside this box to close it.
onClick={(e) => {
e.stopPropagation(); // β
prevents outside handler
alert("Inside button clicked β outside click ignored.");
}}
>
Inside Button
) : (
onClick={(e) => {
e.stopPropagation(); // β
prevents hook from treating this as outside click
setOpen(true);
}}
>
Reopen Box
)}
);
};
``- handler: Callback invoked when an outside click occurs. Receives the event object.
- returns: A React ref you can assign to any DOM element.
MIT Β© 2025 Junaid Akbar