Christoffer Hennie
Christoffer Hennie

Reputation: 79

React hide dropdown menu when lose focus

I am following Fireship's Advanced Dropdown Menu video on YouTube. After I finished the video, I noticed that the menu stays open until the page reloads. Is there a way to make it disappear when it loses focus, for example when the user clicks outside the menu? Not only when the user clicks on the nav icon.

Upvotes: 0

Views: 3079

Answers (1)

Yosef Tukachinsky
Yosef Tukachinsky

Reputation: 5895

Assuming button is ref for a dropdown trigger element, and isOpen add a class to open the dropdown:

const [isOpen, setIsOpen] = useState(false);
const button = useRef(null);
useEffect(() => window.addEventListener('click', ev => {
    if(button.current && button.current.contains(ev.target)) {setIsOpen(!isOpen)}
    else {setIsOpen(false)}
}));

on the DOM, the trigger element:

<div ref={button}>...</div>

the dropdown menu

<div className={isOpen ? 'open' : ''}>...</div>

Upvotes: 1

Related Questions