3

My app has a couple of tabs created with createBottomTabNavigator containing each some screens. I'm trying to achieve the following : when a user clicks on a tab, I would like my app to render the first/home screen of that tab.

So I found this line navigation.dispatch(StackActions.popToTop()) on the internet which is supposed to reset all screens/routing to the initial screen. The code below works properly IF there are some screens to pop (i.e. if user clicks through some screens). If you're on the first screen and you click on this tab, the error below appears.

The error can't be handled with a try/catch. How can I avoid triggering this error ? Can I check somehow if there are some screens to go back to ? It says it would work in production, but when testing with expo, the error is a nightmare to work through...

const Tab = createBottomTabNavigator();
const MyTabs = () => {
    return (
        <Tab.Navigator
            initialRouteName="FirstTab"
        >
            <Tab.Screen
                name="FirstTab"
                component={FirstTabScreen} // This is my createStackNavigator()
                options={{
                    tabBarLabel: "Scan",
                    tabBarIcon: () => <Icon name="camera" />,
                }}
                listeners={({ navigation, route }) => ({
                    tabPress: (e) => {
                        e.preventDefault();
                        navigation.dispatch(StackActions.popToTop());
                        navigation.navigate("FirstTab");
                    },
                })}
            />
        </Tab.Navigator>
    );
};

return (
    <NavigationContainer>
        <MyTabs />
    </NavigationContainer>
);
Waroulolz
  • 297
  • 9
  • 23

1 Answers1

2

There is a navigation.canGoBack() that you can use to achieve this. If it does not work, you could try this solution from another stackoverflow thread.

Quentin Grisel
  • 4,794
  • 1
  • 10
  • 15
  • If I tested it correctly, it seems that navigation.canGoBack() returns true if you click on another tab the same way it returns true if you navigate to another screen in the same tab. So checking it with an if (navigation.canGoBack()) is not really effective... I tried navigation.dangerouslyGetParent() but it's always undefined... – Waroulolz May 24 '20 at 22:58
  • Could you please provide a repro please ?A working expo would be nice, I don't really understand the structure of your project. – Quentin Grisel May 24 '20 at 23:12