DEV Community

Hamsa H N
Hamsa H N

Posted on

Trigger an onClick event outside the child element, works for nested child components too.

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:

  1. Add click eventListener to the parent div.
  2. Exclude the child div.
  3. 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.
image

2. Exclude the child div
Exclude the child component, otherwise we end up closing the dropdown/menuitems even when these items are clicked.

image

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.

image

Happy coding:)

Discussion (2)

Collapse
mishrabhavesh profile image
Bhavesh Mishra

Is adding domElement.onClick = callback func equivalent to domElement.addEventListener('click', callback func) ?

Collapse
mohammad_seyfayi profile image
Mohammad Seyfayi

In this solution the chid element have to know the className of its parent
And I think it's a bad practice