Search code examples
react-nativesimplemodal

Closing React native Modal is not working


I want to have a Modal in React native like below, where the Modal should close onPress to the 'close' text. demo picture here

The ModalProps is coming from the previous component as true. OnPress to 'close' I want the 'visible' to be false and the Modal to be closed. My OS is Android. The Code is below:

type ModalProps = {
    visible: boolean  // visible = true here from the previous screen
}


const closeModal = ():void => {
    // code to make the visible false
}

function myModal ({visible}: ModalProps) {
    return (
        <Modal visible={visible}>
            <View>
                <Text> this is my Modal</Text> 
            </View>
            <View>
                <Text onPress={() => this.closeModal()}>Dismiss</Text>
            </View>
        </Modal>
    );
}

export default myModal;

How can I do this?


Solution

  • Your parent component should have a state like modalVisible to handle the modal visibility. So your parent component should pass the function prop like onPressClose

    ParentComponent:

    import React, {useState} from 'react';
    import { View, Text } from 'react-native';
    import Modal from 'react-native-modal';
    
    function ParentComponent() {
    
      const [visible, setVisible] = useState(true); // Starts with what visibility you want.
    
      return (
        <MyModal visible={visible} onPressClose={() => setVisible(false)} />
       );
    }
    
    

    ModalComponent:

    // imports...
    
    function MyModal ({visible, onPressClose}){
      return (
        <Modal visible={visible}>
          <View>
             <Text> this is my Modal</Text> 
          </View>
          <View>
            <Text onPress={onPressClose}> Dismiss </Text>
          </View>
        </Modal>
    
       );
      }