useClickAway

Detect clicks outside of specific component with useClickAway.

Install:

npm i @uidotdev/usehooks

Description:

The useClickAway hook is a useful for detecting clicks outside a specific component. It allows you to pass a callback function that will be triggered whenever a click occurs outside the component’s area. This hook is particularly helpful when implementing dropdown menus, modals, or any other UI elements that need to be closed when the user clicks outside of them. By attaching event listeners to the document, the hook checks if the click target is within the component’s reference, and if not, it invokes the provided callback function.

Parameters

NameTypeDescription
callbackfunctionThe callback function that is provided as an argument to useClickAway. This function is invoked whenever a click event is detected outside of the referenced element. The event object from the click is passed to this callback function.

Return Values

NameTypeDescription
refReact refThis is a ref object returned by the hook. It should be attached to a React element to monitor click events. The ref provides a way to access the properties of the element it is attached to.

Demo:

Example:

More Hooks:

Sort: