Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

First of all correct usage for toggle function is

setIsOpen(prevIsOpen => !prevIsOpen);

And regarding your question. Just wrap all screen into touchable component without any feedback.

const close = () => isOpen && setIsOpen(false);

return (
    <TouchableWithoutFeedback onPress={close} style={{ flex: 1 }}>
      <View>
        <TouchableOpacity onPress={toggle}>
          <Text>Open select</Text>
        </TouchableOpacity>
        <View>
          {isOpen && options.map(({value, label}) => <View key={value} onPress={toggle}>{label}</View>)}
        </View>
      </View>
    </TouchableWithoutFeedback>
);
about 4 years ago · Juan Pablo Isaza Report

0

you can use TouchableWithoutFeedback

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!