Modal

The Navigation router works with the built-in Modal component from React Native. Like the Navigation router, the Modal component is 100% native on Android and iOS. You can see how to configure it on the React Native website. In our email example, we add a 'Create Contact' button to the contacts list. When pressed, we display a modal to collect the contact's name and number.

import {Modal} from 'react-native';

<Modal
  visible={modalVisible}
  onRequestClose={() => setModalVisible(false)}>
  <Contact />
</Modal> 

Navigating in a Modal

A modal can have its own stack of scenes independent of the main stack. Inside the Modal, you render a NavigationStack with its own StateNavigator. We need two scenes in the modal in our email example. The first collects the new contact's name and number and the second collects their address. We create a StateNavigator with a State for each scene.

const contactNavigator = new StateNavigator([
  {key: 'contact'},
  {key: 'address', trackCrumbTrail: true}
]);

Then we render the NavigationStack inside the Modal and assign it the StateNavigator we just created.

<Modal>
  <NavigationHandler stateNavigator={contactNavigator}>
    <NavigationStack>
      <Scene stateKey="contact"><Contact /></Scene>
      <Scene stateKey="address"><Address /></Scene>
    </NavigationStack>
  </NavigationHandler>
</Modal> 

Handling the Android Back Button

When the user presses the Android back button inside a modal, React Native calls the onRequestClose prop. Normally this is where you’d close the modal. But if you have a stack of scenes you might want to navigate to the start of the stack before closing the modal. If you wrap the Modal in a ModalBackHandler you have access to a handleBack function that pops the scene on the top of the stack.

import {ModalBackHandler} from 'navigation-react-native';

<ModalBackHandler>
  {handleBack => (
    <Modal
      onRequestClose={() => {
        if (!handleBack())
          this.setState({modalVisible: false});
      }}>
      <NavigationHandler stateNavigator={contactNavigator}>
        <NavigationStack>
          <Scene stateKey="contact"><Contact /></Scene>
          <Scene stateKey="address"><Address /></Scene>
        </NavigationStack>
      </NavigationHandler>
    </Modal>        
  )}
</ModalBackHandler>