Introduction
ClickAwayListener is a utility component that listens for click events that occur somewhere in the document, outside of the element itself. This is useful for closing menus, dialogs, or other components when the user clicks outside of them.Basic Usage
Props
children
- Type:
React.ReactElement - Required: Yes
onClickAway
- Type:
(event: MouseEvent | TouchEvent) => void - Required: Yes
disableReactTree
- Type:
boolean - Default:
false
true, the React tree is ignored and only the DOM tree is considered. This prop changes how portaled elements are handled.
mouseEvent
- Type:
'onClick' | 'onMouseDown' | 'onMouseUp' | 'onPointerDown' | 'onPointerUp' | false - Default:
'onClick'
false.
touchEvent
- Type:
'onTouchStart' | 'onTouchEnd' | false - Default:
'onTouchEnd'
false.
Usage with Portal
When using ClickAwayListener with portaled content (like with Portal or Modal), you may need to use thedisableReactTree prop:
Leading Edge
By default, the component responds to the trailing edge of the click event (mouseup or touchend). You can make it respond to the leading edge by setting themouseEvent and touchEvent props:
Accessibility
By default, ClickAwayListener will add anonClick handler to its child. This may conflict with existing event handlers. Make sure to handle this appropriately in your implementation.