Skip to content

useClickAway

Execute a function when the user clicks outside a target element.

Parameters

  1. a click event callback funtion.
  2. and some options:
NameTypeDescription
refRefObjectthe target element reference.

Return Values

a ref object of the target element.

TIP

If you want to cancel the click away function, just use stopPropagation method of the click event:

ts
const handleClick = (event) => {
  event.stopPropagation();
  ...
}
const handleClick = (event) => {
  event.stopPropagation();
  ...
}

Example Usage

tsx
import { useClickAway } from 'react-pre-hooks';

export default function Example() {
  const ref = useClickAway(() => ref.current.classList.add('hide'));

  const showModal = e => {
    e.stopPropagation(); // cancel the click away function
    ref.current.classList.remove('hide');
  };

  return (
    <main>
      <button onClick={showModal}>Open</button>
      <div id="modal" ref={ref} className="hide">
        <strong>Click Outside!</strong>
        <p>to close this modal.</p>
      </div>
    </main>
  );
}
import { useClickAway } from 'react-pre-hooks';

export default function Example() {
  const ref = useClickAway(() => ref.current.classList.add('hide'));

  const showModal = e => {
    e.stopPropagation(); // cancel the click away function
    ref.current.classList.remove('hide');
  };

  return (
    <main>
      <button onClick={showModal}>Open</button>
      <div id="modal" ref={ref} className="hide">
        <strong>Click Outside!</strong>
        <p>to close this modal.</p>
      </div>
    </main>
  );
}

Released under the MIT License.