'Is there any other way to hide dropdown menu when clicked outside?
So, I am creating a dropdown menu in React and if I click outside the dropdown menu, it should close. For that, I am currently using click eventListeners. Is there any other way that can be used instead of using eventListeners? I tried with onFocus and onBlur, but that doesn't seem to work.
Here's the code snippet:
const [showMenu, setShowMenu] = useState(false);
const dropdownRef = useRef(null);
useEffect(() => {
//hiding the dropdown if clicked outside
const pageClickEvent = (e: { target: unknown }) => {
if (dropdownRef.current !== null && !dropdownRef.current.contains(e.target)) {
setShowMenu(!showMenu);
}
};
//if the dropdown is active then listens for click
if (showMenu) {
document.addEventListener("click", pageClickEvent);
}
//unsetting the listener
return () => {
document.removeEventListener("click", pageClickEvent);
};
}, [showMenu]);
<Button onClick = {() => setShowMenu(!showMenu)} />
{showMenu ? (
<div className="dropdown-content" ref={dropdownRef} >
<a>
...
<a>
</div>
) : null}
Solution 1:[1]
Yes there is. Use an overlay under the menu.
function MyComponent() {
const [menuVisible, setMenuVisible] = useState(false);
return (
<div>
<button className='dropdown-button' onClick={() => setMenuVisible(true)}>Click me</button>
{menuVisible ? (
<ul className='dropdown-menu'>
{/* items go here */ }
</ul>
) : null}
{/* now the important part */}
{menuVisible ? (<div className='overlay' onClick={() => setMenuVisible(false)} />) : null}
</div>
)
}
CSS
.overlay {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: rgba(0, 0, 0, 0.01);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Silviu-Marian |
