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,
callback: () => void
): void;
Parameters
- containerrequired · HTMLElement | HTMLElement[] | null
A single HTML element, an array of HTML elements, or
null
. Ifnull
, no event listener is attached.
- callbackrequired · () => void
A function that is executed when clicking outside the specified container(s).
Return Value
This hook 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>;
}