@trans.eu/use-click-outside

1.0.1 • Public • Published

useClickOutside

A React hook for detecting click events outside of an element.

Live example

Why use this library?

  • it works even when some onClick handler does event.stopPropagation()
  • it works with new window portals
  • it does not treat click on element's portal as external clicks

Usage

const { ref, onClickCapture } = useClickOutside(callback);

The only argument to the hook is a callback function that gets invoked when a click event is detected outside of an element.

The hook returns an object with ref and onClickCapture properties that should be passed to an element.

Property Description
ref A ref object created by the useRef hook with an uninitialized .current property.
onClickCapture An event handler for the click event in the capture phase.

Example code

import React, { useCallback } from 'react';
import useClickOutside from '@trans.eu/use-click-outside';

const Example = () => {
  const onClickOutside = useCallback(() => {
    console.log('Click outside');
  }, []);

  const { ref, onClickCapture } = useClickOutside(onClickOutside);

  return (
    <div ref={ref} onClickCapture={onClickCapture}>
      Element
    </div>
  );
}

Local example

git clone https://github.com/trans-eu/use-click-outside.git
cd ./use-click-outside
npm install
npm run start

and open http://localhost:8080/ in your browser

Package Sidebar

Install

npm i @trans.eu/use-click-outside

Weekly Downloads

7

Version

1.0.1

License

MIT

Unpacked Size

6.17 kB

Total Files

4

Last publish

Collaborators

  • dominikmichalski
  • trans-eu
  • roblan
  • mgrycz
  • kocvrek
  • lszychowiak