Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

How to check if press outside a component in react-native?

$
0
0

I did a custom select but I have the problem to close it if I press outside the select or options. basically the "button" is a TouchableOpacity and when I click on it there appears the list of options. But now I can close it only by choosing one option or clicking back on the select button. Is there a way to check whether I click outside the TouchableOpacity or not? In simple react you can give an Id to the component and check it onClick event to see what you have clicked. Or you can use react's useRef hook which doesn't seem to work with react-native. I have this code (simplified):

const [isOpen, setIsOpen] = useState(false)const toggle = () => { setIsOpen(!isOpen)}//...return (<View><TouchableOpacity onPress={toggle}><Text>Open select</Text></TouchableOpacity><View>    {isOpen && options.map(({value, label}) => <View key={value} onPress={toggle}>{label}</View>)}</View></View>)

As you can see you can call toggle only if you press the select button or an option. I want to call setIsOpen(false) when I click outside the TouchableOpacity box.

Is there a way or library to do it?


Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>