useOnClickRef
About
A hook that creates a callback ref for handling both click and touch events on DOM elements. It automatically prevents default behavior and provides a unified interface for mouse clicks and touch interactions.
Examples
Basic example
Touch-friendly button example
Multiple elements example
Arguments
Argument | Type | Description | Default |
---|---|---|---|
onClick | Function | Callback function to execute when element is clicked/tapped | - |
Returns
Return value | Type | Description | Default |
---|---|---|---|
ref | Callback Ref | A callback ref that should be attached to the target element | undefined |
Behavior
- Event Handling: Listens for both
click
andtouchend
events - Default Prevention: Automatically calls
preventDefault()
on triggered events - Cleanup: Automatically removes event listeners when the component unmounts or when the ref is detached
- Fresh Callbacks: Uses internal optimization to ensure the latest onClick callback is always used
Use Cases
- Creating touch-friendly interactive elements
- Building custom clickable components that work on both desktop and mobile
- Handling click events with automatic preventDefault behavior
- Unifying mouse and touch interactions in a single handler