HSBP
HSBP

Reputation: 765

How to close the modal in react native

I am newbie to react native developing. I want to close the modal component on pressing outside the modal in reactnative. Below is my code.

state = {
    visibleModal : false,
};

_hideModal(){
  this.setState({
    visibleModal: true,
  })
}


render(){
    return(
        <View style={
            [styles.container,
                {backgroundColor: this.state.visibleModal ? 'rgba(47, 60, 73, 0.75)': 'white'}
            ]}>

            <Text>Text Behind Modal</Text>

            { this._renderButton('BUTTON', () => this.setState({ visibleModal: true}) ) }
            <TouchableWithoutFeedback onPress={() => {this._hideModal()}}>
            <Modal animationType={"slide"}
                   transparent={true}
                   visible={this.state.visibleModal}>

                      <View style={styles.modalContent}>
                          <Row />
                      </View>

            </Modal>
          </TouchableWithoutFeedback>
        </View>
    );
}

}

Upvotes: 23

Views: 68874

Answers (3)

Samira Gheibipour
Samira Gheibipour

Reputation: 377

 <Modal animationType={"slide"}
           transparent={true}
           visible={this.state.visibleModal}>
              <TouchableWithoutFeedback onPress={() => {this.close_modal()}}>
                 <View style={styles.modalContent}>
                     ....
                 </View>
             </TouchableWithoutFeedback>
    </Modal>

this is sample of my code when you tap outside to close your modal

than so close_modal function visibleModal get false value

for exp.

this.setState({ visibleModal: false });

Upvotes: -1

Akshay Yeole
Akshay Yeole

Reputation: 17

Question :

To close modal when clicking outside the modal.

Solution:

Just remove function call on TouchableWithoutFeedback,it will work..

    <TouchableWithoutFeedback onPress={() => {}}>
  <Modal animationType={"slide"}
               transparent={true}
               visible={this.state.visibleModal}>

                  <View style={styles.modalContent}>
                      <Row />
                  </View>
        </Modal>
</TouchableWithoutFeedback>

Upvotes: -1

Jigar Shah
Jigar Shah

Reputation: 6223

Just add this prop in Modal

onRequestClose={() => { this.visibleModal(false); } }

It will close your modal on pressing back button

<Modal animationType={"slide"}
   transparent={true}
   visible={this.state.visibleModal}
   onRequestClose={() => { this.visibleModal(false); } }
>

EDIT

Above code will work only on Android as per the document.

For both,

You can add custom button to close modal

<TouchableOpacity
    onPress={() => {
        this.setState({visibleModal: false})
    } }>
    <Image
        style={[styles.modalBackIcon]}
        source={require('../../theme/images/back-icon.png')} />
</TouchableOpacity>

Upvotes: 41

Related Questions