Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dismiss modal when navigating to another screen

Tags:

I have an App with Home Screen, in this screen I'm rendering a Modal which opens on button press, inside the Modal I have a button that is supposed to navigate me to another screen, it's navigating correctly but when I navigate to another screen the modal doesn't disappear, how can i hide it?

Adding the code to demonstrate

Home:

import React, { Component } from 'react';
import Modal from './Modal';

class Home extends Component {
  state = {
    isModalVisible: false
  };

  toggleModal = () =>
    this.setState({ isModalVisible: !this.state.isModalVisible });

  render() {
    const { navigate } = this.props.navigation;

    <Modal
    visible={this.state.isModalVisible}
    navigation={this.props.navigation}
    />
    );
  }
}

export default Home;

Modal:

import React, { Component } from "react";
import Modal from "react-native-modal";

class Modal extends Component {

  render() {
    const { navigate } = this.props.navigation;

    return (
        <Modal
        isVisible={this.props.visible}>
          <Button onPress={() => {navigate('Main')}}>
            >Button</Text>
          </Button>
        </Modal>
    );
  }
}

export default Modal;
like image 948
Judy M. Avatar asked Sep 18 '18 17:09

Judy M.


People also ask

How do I close modal react navigation?

Modals should always have a dismiss button, on left-to-right devices it's typically placed as a left button in the TopBar. After we've added our dismiss button, we need to dismiss the modal when the button is pressed.

What is navigate replace?

The replace options property is a REPLACE navigation action. It's a redirect, replacing the current entry in the history stack versus PUSHing a new entry onto the top like a regular navigation. navigate(path); // PUSH, navigate navigate(path, { replace: true }); // REPLACE, redirect.


1 Answers

Ideally you should wait for the setState to finish inside the callback and then navigate to the screen, since the methods are async and may disrupt the state if navigate is called before setState has finished completing.

Also parent should control the state of the child.

Home

onNavigate = () => {
  this.setState({isModalVisible: false}, () => this.props.navigation.navigate('Main')
}

<Modal
    visible={this.state.isModalVisible}
    onNavigate={this.onNavigate}
 />

Modal

<Modal
  isVisible={this.props.visible}>
    <Button onPress={this.props.onNavigate}>
      <Text>Button</Text>
    </Button>
</Modal>
like image 53
Pritish Vaidya Avatar answered Sep 28 '22 17:09

Pritish Vaidya