Created
July 8, 2019 21:07
-
-
Save lmosele/b84e0c02715496b9cfacf0c8f62ee737 to your computer and use it in GitHub Desktop.
React On Click Outside of Element Hook
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 { useState, useEffect, useRef } from "react"; | |
export default function useComponentVisible(initialIsVisible) { | |
const [isComponentVisible, setIsComponentVisible] = useState( | |
initialIsVisible | |
); | |
const ref = useRef(null); | |
const handleClickOutside = event => { | |
if (ref.current && !ref.current.contains(event.target)) { | |
setIsComponentVisible(false); | |
} | |
}; | |
useEffect(() => { | |
document.addEventListener("click", handleClickOutside, true); | |
return () => { | |
document.removeEventListener("click", handleClickOutside, true); | |
}; | |
}); | |
return { ref, isComponentVisible, setIsComponentVisible }; | |
} |
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
// clicking outside of div will hide <p> | |
const Menu = props => { | |
const { ref, isComponentVisible } = useComponentVisible(true); | |
return ( | |
<div ref={ref}> | |
{isComponentVisible && <p>{props.children}</p>} | |
</div> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment