DEV Community

Rashed Iqbal
Rashed Iqbal

Posted on • Updated on

How to Handle Outside Clicks in React with TypeScript

React is a powerful library for building web applications, but sometimes you need to handle events that occur outside of your components. This can be tricky because React's event handling is based on a component hierarchy, and events outside that hierarchy are not automatically detected.

There are several libraries out there that can help you handle outside clicks, such as outsideclick-react. However, in this tutorial, we will show you how to implement your own hook to handle outside clicks in React using TypeScript.

To create a custom hook that listens for outside clicks, we can make use of the useRef and useEffect hooks provided by React. Here's an example implementation of the useOutsideClick hook:

import { useEffect, useRef } from 'react';

export const useOutsideClick = (callback: () => void) => {
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent | TouchEvent) => {
      if (ref.current && !ref.current.contains(event.target as Node)) {
        callback();
      }
    };

    document.addEventListener('mouseup', handleClickOutside);
    document.addEventListener('touchend', handleClickOutside);


    return () => {
      document.removeEventListener('mouseup', handleClickOutside);
      document.removeEventListener('touchend', handleClickOutside);
    };
  }, [callback]);

  return ref;
};

Enter fullscreen mode Exit fullscreen mode

In this implementation, the useOutsideClick hook takes a callback function as an argument, which will be triggered when a click event occurs outside of the specified element.

The hook returns a ref object, which can be attached to the root element of the component that needs to listen for outside clicks. When a click event occurs outside of this element, the callback function will be triggered.

Here's an example usage of the useOutsideClick hook:

import { useOutsideClick } from './useOutsideClick';

export const MyComponent = () => {
  const ref = useOutsideClick(() => {
    console.log('Clicked outside of MyComponent');
  });

  return (
    <div ref={ref}>
      My Component
    </div>
  );
};

Enter fullscreen mode Exit fullscreen mode

In this example, the useOutsideClick hook is used to create a ref object, which is then passed to the root element of MyComponent. When the user clicks outside of MyComponent, the console.log statement in the callback function will be triggered.

By using the useOutsideClick hook, you can easily handle clicks outside of a specific element in your React components. This provides a simple and effective way to handle events that occur outside of the React component hierarchy.

Latest comments (6)

Collapse
 
evilpaprika profile image
Ilinykh Ivan

This does not work with touch events, be careful!

Collapse
 
diazsasak profile image
Diaz Guntur Febrian

just add event listener for "touchend" too?

Collapse
 
oliviagambitsis profile image
olivia-gambitsis

Thanks so much for writing this!

Collapse
 
kazuwombat profile image
Kazuya Matsumoto

Thank you!

Collapse
 
ostraveller profile image
Faisal Ahmed

Thanks this helped me a lot, I was trying to find the solution here and there and finally found it thanks to you. 😊😊

Collapse
 
fullofdev profile image
Full of Dev

thanks! work like charms!