Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

421
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

0

you can use TouchableWithoutFeedback

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda