Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

428
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

0

you can use TouchableWithoutFeedback

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda