Search code examples
react-nativemodal-dialogrefreact-props

Closing modal in child component React Native


I have two components in react native and I'm unable to close a modal from my child component.

ListTrips - Parent

ModalAddTrip - Child

ListTrips.js

import ModalAddTrip from './ModalAddTrip';
....
....
this.state = {
    isModalAddTripVisible: false
} 
....
handleDismissModalAddTrip = () => {
    this.setState({ isModalAddTripVisible: false });
};

closeModal() {
    this.refs.ModalAdd.handleDismissModalAddTrip();
}
....

<ModalAddTrip
    ref="ModalAdd"
    isVisible={this.state.isModalAddTripVisible}
    onBackDropPress={this.handleDismissModalAddTrip}
    closeModal={() => this.closeModal()}
    onRequestClose={this.handleDismissModalAddTrip}
/>

ModalAddTrip.js

<Modal
    isVisible={isVisible}
    onBackdropPress={onBackDropPress}
    closeModal={this.props.child}
>
<Button
    style={{ fontSize: 18, color: 'white' }}
    containerStyle={{
        padding: 8,
        marginLeft: 70,
    }}
    onPress={this.closeModal}
>

I'm unable to close the modal once I open it. I know its something to do with referencing/props but I've messed around with it for hours and I cannot get anywhere. I was trying something along the lines of this.props.closeModal; along with switching the ref to the child component but it didn't work either. inside a function in ModalAddTrip but that wouldn't work either.

Any help is greatly appreciated. Thanks


Solution

  • Here is a solution which I use to handle modal.

    export default class MyModal extends React.Component<Props, State>{
    
      constructor(props: Props){
        super(props);
        this.state = {
          visible: false,
        }
      }
    
      // Use this method to toggle the modal !
      toggleModal = () => {
        this.setState({visible: !this.state.visible});
      }
    
    
      render(){
        return(
          <Modal
          isVisible={this.state.visible}
          hideModalContentWhileAnimating
          onBackdropPress={() => {
            this.toggleModal();
          }}
          useNativeDriver
          >
            <View style={{backgroundColor: "white", padding: 5}}>
            </View>
          </Modal>
        );
      }
    }
    

    If I press behind it, the modal will close -> it can close itself.

    Now to manage it from the parent component just get a ref from your modal :

      <MyModal 
        ref={ref => {
          this.myModal = ref;
        }}
      />
    

    And you can toggle it from the parent component :

    toggleMyModal = () => {
        if(this.myModal){
          this.myModal.toggleModal();
        }
      }
    

    Let me know if you got it working :)