hfalk
hfalk

Reputation: 13

Reset stack inside a tab on tab double press using React Navigation 5

I am wondering how to reset a stack inside a BottomTabNavigator if the Tab is focused and pressed.

This is the code I have so far:

const Stack = createStackNavigator<MainStackParams>()
const BottomTab = createBottomTabNavigator<TabNavigatorParams>()
const navigationRef = React.useRef()

> Blockquote

<NavigationContainer ref={navigationRef}>
    <Stack.Navigator mode="modal">
            <Stack.Screen
                name={MainAppRoute.BOTTOM_TAB_NAVIGATOR}
                component={BottomTabNavigator}
            />
            ...
    </Stack.Navigator>
</NavigationContainer>

function BottomTabNavigator() {
    return (
        <BottomTab.Navigator>
            <BottomTab.Screen
                name={TabNavigatorRoute.SOME_STACK}
                component={SomeStack}
                listeners={{tabPress: e => {

                    // TODO: Reset stack in current tab (unsure how to do this)

                }}}
            />
            ...
        </BottomTab.Navigator>
    )
}

In the TODO (in the code snippet) the following should probably be done:

Have any one been able to do this yet? Appreciate all answers :)

Upvotes: 1

Views: 2010

Answers (1)

Karli Ots
Karli Ots

Reputation: 779

Okey, basically you have 2 options to manage this, first is to check navigation state, but as i found out, it works only on IOS device, android does not do anything.

This piece of code navigated to first screen from this stacknavigator

<Tab.Screen name={`DeviceNavigatorTab`} component={DeviceNavigator} options={{
            tabBarIcon: ({tintColor}) => <Image source={require('../../images/feather_home-menu.png')} style={{width: 26, height: 26, tintColor}}/>,
        }} listeners={({ navigation, route }) => ({
            tabPress: e => {
                if (route.state && route.state.routeNames.length > 0) {
                    navigation.navigate('Device')
                }
            },
        })} />

The other solution, and even better, works on android and IOS operating systems

DeviceNavigatorTab this is tab navigator screen name, {screen: 'Device'} is the first stack screen name in sub stack navigator, hope it helps

<Tab.Screen name={`DeviceNavigatorTab`} component={DeviceNavigator} options={{
            tabBarIcon: ({tintColor}) => <Image source={require('../../images/feather_home-menu.png')} style={{width: 26, height: 26, tintColor}}/>,
        }} listeners={({ navigation }) => ({
            tabPress: e => {
                navigation.navigate('DeviceNavigatorTab', { screen: 'Device' });
            },
        })} />

It is not actually resetting the navigators, it just goes to specified screen inside that tab navigator.

Upvotes: 2

Related Questions