Skip to content

useOutsideClickEffect ​

useOutsideClickEffect is a React hook that triggers a callback when a click event occurs outside the specified container(s). It is useful for closing modals, dropdowns, tooltips, and other UI components when clicking outside.

Interface ​

ts
function useOutsideClickEffect(
  container: HTMLElement | (HTMLElement | null)[] | null,
  callback: () => void
): void;

Parameters ​

  • containerrequired · HTMLElement | (HTMLElement | null)[] | null

    A single HTML element, an array of HTML elements or null values, or null. null entries are ignored. If no HTML elements remain, the callback is not executed.

  • callbackrequired · () => void

    A function that is executed when clicking outside the specified container(s).

Return Value ​

This function does not return anything.

Example ​

tsx
import { useOutsideClickEffect } from 'react-simplikit';
import { useState } from 'react';

function Example() {
  const [wrapperEl, setWrapperEl] = useState<HTMLDivElement | null>(null);

  useOutsideClickEffect(wrapperEl, () => {
    console.log('Outside clicked!');
  });

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

Released under the MIT License.