Hooks/UI & DOM/useClickOutside

useClickOutside

A custom React hook to detect clicks outside a specified element.

useClickOutside is a custom React hook that allows you to detect clicks outside of a specified element. This is particularly useful for closing dropdowns, modals, or any UI component when the user clicks outside of it.

Example

Loading...

Install

npx shadcn@latest add https://unlogg.com/r/use-click-outside.json
pnpm dlx shadcn@latest add https://unlogg.com/r/use-click-outside.json
bunx shadcn@latest add https://unlogg.com/r/use-click-outside.json

Notes

  • useClickOutside is useful for closing popovers, modals, dropdowns, or any UI element when a user clicks or taps outside of it.
  • You can specify which events to listen for (e.g., mousedown, touchstart).
  • You can provide additional nodes that should not trigger the outside click handler (e.g., buttons or other elements).
  • The hook returns a ref that must be attached to the element you want to monitor for outside clicks.
  • The handler will not be called if the click is inside the referenced element or any of the excluded nodes.

API Reference

Parameters

PropTypeDefault
nodes?
(Element | null)[]
[]
events?
string[]
['mousedown', 'touchstart']
handler
(event: Event) => void
-

Returns

PropTypeDefault
ref?
React.RefObject<T>
-