I have a custom dropdown button which opens a dropdown menu in React Native. To handle the state of dropdown I use Redux Toolkit. What most confuses me is the approach to detect clicks outside that dropdown menu to dispatch an action to hide the dropdown.
I have searched for possible solutions and here's the list of possible solutions I came across so far:
1. Wrapping inside TouchableWithoutFeedback Component
Wrap the whole app or screen inside TouchableWithoutFeedback
component to detect presses outside the element. If user presses the Touchable component then the press is surely outside the dropdown menu so we can close the dropdown using onPress
event handler.
Cons:
- If users presses somewhere outside both dropdown menu and
TouchableWithoutFeedback
, like another custom button, text input component etc. then the press event will be handled by these other children components and will not reach toTouchableWithoutFeedback
component'sonPress
handler. To make sure dropdown menu is hidden after user presses these other components, I will have to manually handle their specific press handlers. This will cause in less managable code and a lot of code duplication. FlatList
or otherScrollView
like scrollable components have a buggy scroll behaviour. Sometimes scroll events don't register by these components.
2. Setting hitSlope/hitBox of dropdown menu to very high number
When we set the hitSlope or hitBox prop of dropdown menu's outer Touchable component we can register the presses outside the menu. But this is an ugly approach in my opnion because it may overlap with other pressable components and could cause bugs.
Cons
- Ugly code
- Huge hitSlope may overlap with other pressable components and could cause bugs