Say, you have a non-modal component like dropdown or the menu and I'm sure one thing you'd definitely need is to close/hide the content of the component when user clicks outside the component too, not just on the dropdown or menu button.
It is one of the common requirements and here's how its achieved:
- Add click eventListener to the parent div.
- Exclude the child div.
- Remove the click eventListner on component unmount.
1. Add click eventListener to the parent div
Assign a id to the parent and top-level child div element, if not already. On componentDidMount() of the child element, add a click event listener as shown in the below code.
2. Exclude the child div
Exclude the child component, otherwise we end up closing the dropdown/menuitems even when these items are clicked.
Make sure we use !topLevelChild.contains(e.target) and not topLevelChild !== e.target because all the nested child elements are also supposed to be excluded. Choosing the later works fine if there is only one child div element.
3. Remove the click eventListner on component unmount
An important step not to leave behind is removing the event listener when the child unmounts from the DOM, to avoid unnecessary addition of the event listners every time its expanded.
Happy coding:)
Top comments (4)
Is adding
domElement.onClick = callback func
equivalent todomElement.addEventListener('click', callback func)
?Yes, they does the same thing, the first one uses the other.
In this solution the chid element have to know the className of its parent
And I think it's a bad practice
This is one of the approaches that I could think of. Please let me know if there is a way to avoid child element not having to know the parent's className. Would love to learn.