Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close the modal in react native

Tags:

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>
    );
}

}

like image 426
HSBP Avatar asked Jul 21 '17 08:07

HSBP


1 Answers

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>
like image 160
Jigar Shah Avatar answered Oct 06 '22 08:10

Jigar Shah