shira
shira

Reputation: 394

react native: Android back button does not go back on the first click when I am inside the TopTabNavigator

The Android back button does not go back on the first click when I am inside the TopTabNavigator. What actually happens is that the tab goes left and right and only after a few presses of the Android back button only then it go back. How can such a thing be prevented and fix ?

in my example i have top tab navigator, and i want know how to prevented the situation that Makes navigation play between tabs and only with the second or third press of the Android back button take me back

import * as React from 'react';
import { Text, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createMaterialTopTabNavigator } from '@react-navigation/material-top-tabs';

function HomeScreen() {
  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>Home!</Text>
    </View>
  );
}

function SettingsScreen() {
  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>Settings!</Text>
    </View>
  );
}

const Tab = createMaterialTopTabNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Tab.Navigator>
        <Tab.Screen name="Home" component={HomeScreen} />
        <Tab.Screen name="Settings" component={SettingsScreen} />
      </Tab.Navigator>
    </NavigationContainer>
  );
}

Upvotes: 0

Views: 2041

Answers (2)

M&#225;rio Prada
M&#225;rio Prada

Reputation: 2158

Try this:

React.useEffect(() => {
    const backAction = () => {
      if (!navigation.canGoBack()) {
        BackHandler.exitApp();
        return true;
      }

      if (onGoBack) {
        onGoBack();
        return true;
      }

      navigation.goBack();
      return true;
    };

    const backHandler = BackHandler.addEventListener(
      'hardwareBackPress',
      backAction
    );

    return () => {
      backHandler.remove();
    };
  }, [onGoBack, navigation]);

Upvotes: 1

satya164
satya164

Reputation: 10145

export default function App() {
  return (
    <NavigationContainer>
      <Tab.Navigator backBehavior="none">
        <Tab.Screen name="Home" component={HomeScreen} />
        <Tab.Screen name="Settings" component={SettingsScreen} />
      </Tab.Navigator>
    </NavigationContainer>
  );
}

https://reactnavigation.org/docs/bottom-tab-navigator#backbehavior

Upvotes: 1

Related Questions