I am trying to open a modal from another component. this is in my parent component:
const [modalVisible, setModalVisible] = useState(false);
<TouchableOpacity
style={styles.gateBtn}
onPress={() => {
setModalVisible(true);
}}
>
<Text style={styles.gateBtnText}>Show Modal</Text>
<OpenModal isModalVisible={modalVisible} />
</TouchableOpacity>
and this is my OpenModal.js
import React, { useState } from "react";
import {
StyleSheet,
View,
Text,
Alert,
Modal,
TouchableHighlight,
} from "react-native";
function OpenModal(props) {
const [modalVisible, setModalVisible] = useState(false);
return (
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
Alert.alert("Modal has been closed.");
}}
>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<Text style={styles.modalText}>Hello World!</Text>
<TouchableHighlight
style={{ ...styles.openButton, backgroundColor: "#2196F3" }}
onPress={() => {
setModalVisible(!modalVisible);
}}
>
<Text style={styles.textStyle}>Hide Modal</Text>
</TouchableHighlight>
</View>
</View>
</Modal>
);
}
const styles = StyleSheet.create({
centeredView: {
flex: 1,
justifyContent: "center",
alignItems: "center",
marginTop: 22,
},
modalView: {
margin: 20,
backgroundColor: "white",
borderRadius: 20,
padding: 35,
alignItems: "center",
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 5,
},
openButton: {
backgroundColor: "#F194FF",
borderRadius: 20,
padding: 10,
elevation: 2,
},
textStyle: {
color: "white",
fontWeight: "bold",
textAlign: "center",
},
modalText: {
marginBottom: 15,
textAlign: "center",
},
});
export default OpenModal;
however It seems like I am doing something wrong,
I am trying to pass modalVisible
to OpenModal by using isModalVisible={modalVisible}
and modalVisible
is already defined as false, when clicking on the button it becomes true, but in my OpenModal component It seems like its undefined, and it doesnt open the modal at all. What am I missing here?
you need to pass in the setModalVision, then use the props.modalVisible from the parent component.
in parent
child component