-1

I'm trying to fix an issue with a component that whenever I click outside its window it works as expected except for when I click on buttons from other components which have their own functionality.

onClickOutside = (e) => {
  const $container = $(`#${escapeDots(this.id)}`);
  if (this.isEventOutsideElement($container, e)) {
    this.onCloseComponent();
  }
  if (e) {
    e.stopPropagation();
  }
}

This code manages the event when a click is outside my component which then closes it here

componentWillUnmount() {
  document.removeEventListener('click', this.onClickOutside);
  document.removeEventListener('touchstart', this.onTouchOutside, true);
}

The issue I'm getting here is that "element" is empty when I click on the buttons I mentioned, but when I click elsewhere it gets a div with length 1

isEventOutsideElement(element, event) {
  return element.length && !element.is(event.target) && element.has(event.target).length === 0;
}

I'm not sure how can I make this component recognize those buttons so it closes before doing the actions built into the buttons.

I tried to implement a close action on the component where the other buttons are located but it didn't work.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181

1 Answers1

0

I managed to solve it by changing the type of the addEventListener to mousedown, now it works as intended:

componentDidMount() {
document.addEventListener('mousedown', this.onClickOutside);
document.addEventListener('touchstart', this.onTouchOutside, true);}

componentWillUnmount() {
document.removeEventListener('mousedown', this.onClickOutside);
document.removeEventListener('touchstart', this.onTouchOutside, true);}