Playground

useClickOutside

Calls a function when a pointer goes down outside an element, to close menus and popovers.

  • No DOM output. Close popovers with Escape too; this hook covers pointer only.
  • Listens to pointerdown on the document and removes the listener on unmount.

Import

import '@monoline/css';
import {useClickOutside} from '@monoline/react';

Not installed yet? Pick a route.

Copies the source and its styles into your project.

npx monoline add use-click-outside

Usage

import {useState} from 'react';
import {Button, useClickOutside} from '@monoline/react';

function PopoverDemo() {
  const [open, setOpen] = useState(false);
  const ref = useClickOutside<HTMLDivElement>(() => setOpen(false), open);
  return (
    <div>
      <Button variant="line" aria-expanded={open} onClick={() => setOpen((o) => !o)}>Open panel</Button>
      {open && (
        <div ref={ref} role="group" aria-label="Panel">
          <p>Click anywhere outside this panel to close it.</p>
        </div>
      )}
    </div>
  );
}

<PopoverDemo />

Examples

Close on outside click

Behaviour

  • No DOM output. Close popovers with Escape too; this hook covers pointer only.
  • Listens to pointerdown on the document and removes the listener on unmount.