useClickOutside(๐Ÿ‘‡)

August 06, 2020ย ย โ€ขย ย 1 min read

#6 hook of the week

To remind you of the purpose and goal of this week:

For a whole week I'll post a new hook every day. All hooks will support Server-Side Rendering (SSR) and have TypeScript implemented.

I will not describe the hooks in great detail, I'll just present them and show how it's implemented. Then you can do whatever you want with them.

Every hook is also available here, together with a range of other hooks.

View source

Showcase ๐Ÿ”ฅ

Every time you click outside the element below I'll increase the number of clicks by one.

Amount of clicks outside this element:
0.

The hook ๐ŸŽฃ

Trigger a callback when the user clicks outside of a defined element.

I'm using my useEventListener() hook to listen for click event.

import { useCallback, RefObject } from 'react';
import { useEventListener } from './useEventListener';

export const useClickOutside = (
  ref: RefObject<Element>,
  callback: (event: MouseEvent) => void
): void => {
  const handleClick = useCallback(
    (event) => {
      if (!ref.current?.contains(event.target)) {
        callback(event);
      }
    },
    [callback, ref]
  );

  useEventListener({
    type: 'click',
    listener: handleClick
  });
};

Usage

When a user clicks outside of the defined ref element we console.log() its event.

import React, { useRef } from 'react';
import { useClickOutside } from './useClickOutside';

const Component = () => {
  const ref = useRef(null);

  useClickOutside(ref, (event) => {
    console.log(event);
  });

  return <div ref={ref} />;
};

export default Component;

The end ๐Ÿ‘‡

I hope you found this helpful.