raddix

useClickOutside

Detects click and touch events outside from a specific element.

Installation

Install the custom hook from your command line.

npm i @raddix/use-click-outside

Usage

Basic example

In this example, when the user clicks outside the modal it will close.

import { useRef, useState } from 'react';
import { useClickOutside } from '@raddix/use-click-outside';
export const Example = () => {
const [isOpen, setIsOpen] = useState(false);
const refModal = useRef<HTMLDivElement>(null);
useClickOutside(refModal, () => setIsOpen(false));
return (
<>
<button onClick={() => setIsOpen(true)}>Open modal</button>
{isOpen && (
<div ref={refModal}>
<p>Click outside of the modal to close it</p>
</div>
)}
</>
);
};

API

Parameters

NameDescriptionRequiredType
refDOM element being referenced.YesRefObject
callbackThis function is called whenever a click event is detected outside of the referenced element.Yesfunction