2024-09-09 web, development, javascript
Fix Event Bubbling on Select Component from Shandcn/ui
By O. Wolfson
-
Understanding the Issue: Event bubbling occurs when an event is fired on a DOM element and propagates up the DOM tree, potentially triggering event handlers on parent elements. On mobile devices, this can lead to unwanted behaviors, like activating links under a dropdown menu when an item is selected.
-
Solution Overview: The solution involves attaching an
ontouchstart
event handler directly to theSelectContent
component, in the implementation. This handler will prevent the default action of the touch event and stop it from propagating.
Link to original solution found here.
-
Implementing the Fix:
- Use a
ref
callback on theSelectContent
component. - In the callback, check if the
ref
is not null. - Assign an
ontouchstart
handler to theref
that callse.preventDefault()
.
- Use a
-
Code Example:
-
Explanation: The
ref
callback is a function that receives the DOM element as its argument. By setting theontouchstart
property on this element, you directly manipulate the DOM to control the touch event's behavior, preventing it from bubbling up.
This approach ensures that when a user interacts with the SelectContent
component on a mobile device, the touch event does not unintentionally trigger other elements positioned behind or near the dropdown.
For more about Shadcn/UI components, you can visit Shadcn/UI.