React Navigation, close stack navigation inside Drawer navigation by clicking on drawer item

Viewed 638

I have small issue with react navigation v6...

Drawer Navigation:

<Drawer.Navigator drawerContent={(props) => <CustomDrawer {...props} />} >
    <Drawer.Screen name="Search" component={MainStackNavigator} />
    <Drawer.Screen name="Contact" component={ContactScreen} />
</Drawer.Navigator>

Stack navigation:

const MainStackNavigator = () => {
  return (
    <Stack.Navigator initialRouteName="OffersList">
      <Stack.Screen name="OffersList" component={OffersList} />
      <Stack.Screen name="OfferDetails" component={OfferDetails} />
    </Stack.Navigator>
  );
};

and now, when I click on the element Search in drawer navigation then OffersList page is displayed. Next, on the OffersList, when I click on any offer link, then I see OfferDetails view (Stack Navigation) - every thing is ok. Then, when I click on the Contact in drawer nav, and again on Search then I see last opened OfferDetails instead of OfferList. How can I reset this stack navigation when i navigate by drawer?

2 Answers

The user doesn't expect a stack reset, but you think it improves the app experience, just pass unmountOnBlur: true on screenOptions for the Drawer. Your code will be like this:

function MyDrawer() {
  return (
    <Drawer.Navigator
      screenOptions={{
        unmountOnBlur: true
      }}
    >
      <Drawer.Screen name="SomeScreen" component={SomeScreen} />
      <Drawer.Screen name="SomeStack" component={SomeStack} />
    </Drawer.Navigator>
  );
}

You can see the complete example code on an Expo snack. https://snack.expo.dev/@marcelofreires/stackoverflow-questions-71548781

I have the same requirement and I use the useIsFocused hook, in all screens inside the stack except the initial screen I use useEffect to check if isFocused is false then pop the screen out. Here is the example code.

import { useIsFocused } from '@react-navigation/native'

function Sample({navigation}) {
  const isFocused = useIsFocused()
  
  // When the screen is blured, pop it out so when user goes back they will always see the initial screen
  useEffect(() => {
    if (!isFocused) {
      navigation.pop()
    }
  }, [navigation, isFocused])
}
Related