Skip to main content
Version: 5.2.0

useOutsideClick

The useOutsideClick hook allows you to detect clicks that occur outside a specific DOM element, triggering a callback function when this happens.
It’s ideal for closing modals, dropdowns, tooltips, or any component that should dismiss when clicking elsewhere on the page.

Syntax

useOutsideClick(
ref: RefObject<HTMLElement>,
callback: (event: MouseEvent | TouchEvent) => void,
deps?: DependencyList
): void;

Parameters

NameTypeDescription
Refs (required)RefObject<HTMLElement>React ref to the element to detect outside clicks from
Callback (required)(event: MouseEvent or TouchEvent) => voidFunction to run when an outside click is detected.
deps (optional)DependencyListDependency array for when to refresh the callback behavior

Example

It listens for clicks outside the box and automatically hides it whenever you click anywhere else on the page.

import React, { useRef } from 'react';
import { useOutsideClick } from 'react-ui-animate';

export default function App() {
  const ref = useRef(null);

  useOutsideClick(ref, () => {
    alert('You clicked outside box');
  });

  return (
    <>
      <div
        style={{
          display: 'flex',
          justifyContent: 'center',
          height: '100vh',
          alignItems: 'center',
        }}
      >
        <div
          style={{
            padding: 100,
            position: 'absolute',
            left: 0,
            top: 0,
            color: '#a1a1a1',
          }}
        >
          CLICK OUTSIDE
        </div>

        <div
          ref={ref}
          style={{
            width: 200,
            height: 200,
            border: '1px solid #e1e1e1',
            borderRadius: 8,
            backgroundColor: '#f1f1f1',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: '#a1a1a1',
            zIndex: 1,
          }}
        >
          CLICK INSIDE ME
        </div>
      </div>
    </>
  );
}