16

My react-native app has several situations where different modals can be presented. I am wondering what's the best way to accomplish this. In general I see two different approaches:

a) On the root view I always have the Modal-component mounted and simply switch the content, like this...

<View>
    {...}
    <Modal visible={this.props.modal > 0}>
         {this.props.modal === 1 && <ModalContent1 />}
         {this.props.modal === 2 && <ModalContent2 />}
         {this.props.modal === 3 && <ModalContent3 />}
    </Modal>
</View>

b) Every modal brings it's own Modal-component and is mounted somewhere in the tree, near the place it is triggered from.

Which way would you prefer and why?

A question that applies to both approaches is, if the Modal-component should always be mounted and only triggered using the visible-prop. If that's the way to go, I assume approach b) needs more memory, because multiple instances of the Modal-component are created.

Osama Rizwan
  • 615
  • 1
  • 7
  • 19
danielbuechele
  • 3,104
  • 2
  • 18
  • 29

1 Answers1

0

I personally use the Stack Navigator from React Navigation to implement modals within my application. My modals include a "create post modal", "no internet connection modal" among others.

This allows me to access these modals from anywhere in my application and can persist/block other actions directly. To learn more about how to use React Navigation, you can read up on these two links:

  1. To understand the StackNavigator, it has a section specifically for transparent background modals
  2. To learn more about implementing modals in React Navigation in general.
Osama Rizwan
  • 615
  • 1
  • 7
  • 19
lvillacin
  • 154
  • 7