Skip to content

Instantly share code, notes, and snippets.

@cocodrino
Created December 7, 2019 00:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cocodrino/cbb307af6867eb0a46fb1b33097e0ca2 to your computer and use it in GitHub Desktop.
Save cocodrino/cbb307af6867eb0a46fb1b33097e0ca2 to your computer and use it in GitHub Desktop.
click outside event for react
import { useEffect } from "react";
const useOutsideClick = (ref, callback) => {
const handleClick = e => {
if (ref.current && !ref.current.contains(e.target)) {
callback();
}
};
useEffect(() => {
document.addEventListener("click", handleClick);
return () => {
document.removeEventListener("click", handleClick);
};
});
};
export default useOutsideClick;
// this is how use it
import React, { useRef } from "react";
import useOutsideClick from "./useOutsideClick";
function MyComponent() {
const ref = useRef();
useOutsideClick(ref, () => {
alert('You clicked outside')
});
return (
<div className="App">
<div ref={ref}}>
<h4>This is a menu</h4>
<p>This is another content</p>
</div>
<div>
This is a content outside the menu
</div>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment