Skip to content

[ClickAwayListener] failed to rasing onClickAway if you have an element that is removed from DOM when clicked #20197

@seare-kidane

Description

@seare-kidane

If you have a React component/html element that's going to be hidden when clicked, the ClickAwayListener will fail to trigger the onClickAway due to the following condition

    if (
      doc.documentElement &&
      doc.documentElement.contains(event.target) && // <-- event.target no longer in the DOM
      !nodeRef.current.contains(event.target)
    ) {
      onClickAway(event);
    }
  • The issue is present in the latest release.
  • I have searched the issues of this repository and believe that this is not a duplicate.

Current Behaviour 😯

When clicking on an element that gets hidden on click, the ClickAwayListener ignores the click and doesn't trigger onClickAway event.

const handleClick = () => { setShowButton(false); };
const handleClickAway = () => {
  //This is not being called when clicking on the button below
  setClickAwayStatus('Registered onClickAway event from ClickAwayListener');
};

{showButton && (<Button onClick={handleClick}>
  Click to hide
</Button>)}

<p>{clickAwayStatus}</p>

<ClickAwayListener onClickAway={handleClickAway}>
  <div>
    {/* ... */}
  </div>
</ClickAwayListener>

Expected Behaviour 🤔

The onClickAway should be triggered and not care about whether the event source is removed from the DOM

Steps to Reproduce 🕹

Steps:

  1. Open the codesandbox link: https://codesandbox.io/s/festive-dust-fftxt
  2. Click on anywhere except the button labelled "Click to hide"
  3. Notice the the paragraph text changes to "Registered onClickAway event from ClickAwayListener"
  4. After 2 seconds the paragraph text should reset to "Waiting for event"
  5. Now click on the button labelled "Click to hide"
  6. Notice the paragraph text is still "Waiting for event" and will never reset to the previous text since the ClickAwayListener onClickAway event wasn't triggered.

Context 🔦

I'm using the ClickAwayListener with Popper to display a popup menu, and wants it to close when ever I click outside the opened menu. The behaviour works as long as you don't have components or html elements that are removed from DOM on click. I want the menu to close even if i click on other elements that are removed from DOM.

Your Environment 🌎

Tech Version
Material-UI v4.9.5
React v16.12.0
Browser Google Chrome: v80.0.3987.132 (64-bit)

Metadata

Metadata

Assignees

No one assigned

    Labels

    good first issueGreat for first contributions. Enable to learn the contribution process.scope: click away listenerThis is the name of the generic UI component, not the React module!type: bugIt doesn't behave as expected.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions