ideas
ideas copied to clipboard
useClickOutside
Based on idea from this article:
export default function Img({ src }) {
const ref = useClickOutside(handleClickOutside);
function handleClickOutside() {
console.log("clicked outside");
}
return (
<img
ref={ref}
src={src}
alt="comment"
/>
);
}
function useClickOutside(fn) {
const ref = useRef(null);
useEffect(() => {
document.addEventListener("click", handleClick);
return () => document.removeEventListener("click", handleClick);
});
function handleClick(e) {
if (ref.current.contains(e.target)) {
return; // inside the element
}
fn();
};
return ref;
}
It probably doesn't cover some edge cases like React.Protals though.
May want to pass in ref so that it can be used in other hooks. Here's an example: https://usehooks.com/#useOnClickOutside
@gragland yeah, this way it could reuse some existing ref