I am making an application in react native. Here I am able to open Modal at a click and also able to close the modal when clicked inside of the Modal. But I also want to close the Modal when clicked outside of it.
Below is my code:
import React, { useState } from 'react';
import { View, Text, TouchableOpacity, Modal, TouchableWithoutFeedback, Alert } from 'react-native';
function Main({ navigation }) {
const [modalVisible, setModalVisible] = useState(false);
return (
{/* This is not working */}
<TouchableWithoutFeedback onPress={() => { setModalVisible(!modalVisible); }}>
<View>
{/* MODAL FOR LANGUAGE */}
<Modal animationType="slide" transparent={true} visible={modalVisible}>
<View>
<Text>Select Language</Text>
</View>
{/* Close modal*/}
<TouchableOpacity onPress={() => { setModalVisible(!modalVisible); }} >
<Text>English</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => { setModalVisible(!modalVisible); }} >
<Text>Hindi</Text>
</TouchableOpacity>
</Modal>
<View>
{/* Open modal*/}
<TouchableOpacity onPress={() => { setModalVisible(true); }} >
<Text>Language</Text>
</TouchableOpacity>
</View>
</TouchableWithoutFeedback>
);
}
I hope from the comments you can see that I am opening modal when clicked on <Text>Language</Text>
, and I am able to close modal when clicked on <Text>English</Text>
and <Text>Hindi</Text>
, which is inside the modal.
To close the modal when clicked on outside of modal I used <TouchableWithoutFeedback onPress={() => { setModalVisible(!modalVisible); }}>
, but this is not working.
NOTE: I have intentionally removed all the styling part so that my code here looks clean and that I can make it clear about what I want.