React Native built-in Modal is not visible while coming back to screen

Viewed 367

I'm confused in this code little bit, I've two screens, MainScreen and FeedScreen inside NativeStackNavigator, where initialScreenName(screen which will be routed/render first) is MainScreen.

I've a modal nested inside MainScreen , and inside modal there is a button which will navigate to the FeedScreen, while navigating to FeedScreen , Modal was visible but while coming back to MainScreen , Modal is no more visible, and even not openning after clicking on "Show Modal" button...

Where Modal visibility is controlled by state variable, which is also true but still Modal is not visible...

Kindly point out what is going on here because according to me, Modal should be open while coming back to MainScreen from FeedScreen...

Here is code...

function MainScreen({navigation}){

const [modalVisibility, setModalVisibility] = useState(false)

return <View>
          <Text style={{ fontSize: 25 }}>I'm Main Screen...</Text>
          <Text>{String(modalVisibility)}</Text>
          <Button title='Show Modal' onPress={()=>setModalVisibility(true)} ></Button>

          <Modal visible={modalVisibility} onRequestClose={()=>setModalVisibility(false)}>
            <Text>I'm modal with visiblility {String(modalVisibility)}</Text>
            <Button title='Go to Feed' onPress={()=>navigation.navigate('FeedScreen')}/> 
          </Modal>
      </View>

}

function FeedScreen({navigation}) {
return <View>
      <Button title='Go to Main' onPress={()=>navigation.navigate("MainScreen")}></Button>
  </View>
}

function RootStackScreen() {
return (
<NavigationContainer>
  <RootStack.Navigator initialRouteName='MainScreen'>

      <RootStack.Screen name="MainScreen" component={MainScreen}/>
      <RootStack.Screen name="FeedScreen" component={FeedScreen}/>

  </RootStack.Navigator>
</NavigationContainer>
1 Answers

The problem is that the modalVisibility state is not exposed for the FeedScreen meaning the feedscreen cannot access the state, you can use a [context provider] [1] to expose that state to it.

[1]: https://reactjs.org/docs/context.html
Related