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;
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With