Skip to content

Click away listener

Detect if a click event happened outside of an element. It listens for clicks that occur somewhere in the document.

Example

For instance, if you need to hide a menu dropdown when people click anywhere else on your page:

<ClickAwayListener onClickAway={handleClickAway}>
  <div className={classes.root}>
    <button type="button" onClick={handleClick}>
      Open menu dropdown
    </button>
    {open ? (
      <div className={classes.dropdown}>
        Click me, I will stay visible until you click outside.
      </div>
    ) : null}
  </div>
</ClickAwayListener>

Notice that the component only accepts one child element. You can find a more advanced demo on the Menu documentation section.

Portal

The following demo uses Portal to render the dropdown into a new "subtree" outside of current DOM hierarchy.

<ClickAwayListener onClickAway={handleClickAway}>
  <div>
    <button type="button" onClick={handleClick}>
      Open menu dropdown
    </button>
    {open ? (
      <Portal>
        <div className={classes.dropdown}>
          Click me, I will stay visible until you click outside.
        </div>
      </Portal>
    ) : null}
  </div>
</ClickAwayListener>