Created
December 7, 2019 00:51
-
-
Save cocodrino/cbb307af6867eb0a46fb1b33097e0ca2 to your computer and use it in GitHub Desktop.
click outside event for react
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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