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;
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.
onNavigate = () => {
this.setState({isModalVisible: false}, () => this.props.navigation.navigate('Main')
}
<Modal
visible={this.state.isModalVisible}
onNavigate={this.onNavigate}
/>
<Modal
isVisible={this.props.visible}>
<Button onPress={this.props.onNavigate}>
<Text>Button</Text>
</Button>
</Modal>