Skip to content

Instantly share code, notes, and snippets.

@lmosele
Created July 8, 2019 21:07
Show Gist options
  • Save lmosele/b84e0c02715496b9cfacf0c8f62ee737 to your computer and use it in GitHub Desktop.
Save lmosele/b84e0c02715496b9cfacf0c8f62ee737 to your computer and use it in GitHub Desktop.
React On Click Outside of Element Hook
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 };
}
// 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