A react hook to handle clicks outside an element.
- Attach a ref to the element outside which you want to watch clicks.
- Call the hook. Pass the ref as the first argument and the handler as the second.
- ???
- PROFIT
If the handler is a simple () => {}
and if needed wrap it a useCallback
import { useOutsideClick } from 'react-handle-outside-click';
const App = () => {
const ref = React.useRef()
const handleOutsideClick = () => {
console.log("hello")
}
useOutsideClick(ref, handleOutsideClick);
return (
<div ref={ref}>
Hello World
</div>
);
};
import { useOutsideClick } from 'react-handle-outside-click';
const App = () => {
const ref = React.useRef<HTMLDivElement>(null)
const handleOutsideClick = () => {
console.log("hello")
}
useOutsideClick(ref, handleOutsideClick);
return (
<div ref={ref}>
Hello World
</div>
);
};