Block/Disable tabs in TabNavigator - react-navigation

Viewed 12822

I have a TabNavigator as shown in the picture. Header Image

I am using TabNavigator for creating these tabs as below.

const Tab_Navigator = TabNavigator({
    First:{
        screen: First,
    },
    Second:{
        screen: Second,
    },
    Third:{
        screen: Third,
    },

Now I want to block/disable "Second" and "Third" tabs. It should be visible but one shouldn't able to navigate to them.

I tried blocking these tabs as shown here but I guess I am missing something. My try:

Tab_Navigator.router.getStateForAction = (action, state) => {
if( action.type === NavigationActions.navigate({ routeName: "Second"}) ||
    action.type === NavigationActions.navigate({ routeName: "Third"}))
{
    return null;
}

return Byte.router.getStateForAction(action, state);

};

4 Answers

You have to use tabBarOnPress propert under defaultNavigationOptions, and check the route name to which you dont want to navigate return them null else return defaultHandler. Please check the following code

const Tab_Navigator = createBottomTabNavigator({
   First:{
        screen: First,
    },
    Second:{
        screen: Second,
    },
    Third:{
        screen: Third,
    }
}, defaultNavigationOptions: ({ navigation }) => ({
      tabBarOnPress: ({ navigation, defaultHandler }) => {
        if (
          navigation.state.routeName === "Second" ||
          navigation.state.routeName === "Third"
        ) {
          return null;
        }
        defaultHandler();
      },})

This is my solution to disable and completely take control over the tabBarButton in React Navigation 6.

// Defining the disabled tabBarButton component
//
const DisabledTabBarButton = ({ style, ...props }: BottomTabBarButtonProps) => (
  <Pressable disabled style={[{ opacity: 0.2 }, style]} {...props} />
)

const Tab = createBottomTabNavigator()

const Router = () => (
<Tab.Navigator>
  <Tab.Screen name="Screen 1" />
  <Tab.Screen name="Screen 2"
    options={{
      // Applying the disabled button
      tabBarButton: DisabledTabBarButton,
    }}
  />
</Tab.Navigator>

export default Router

For Version 5.x+ there's a new way to do it.

<Tabs.Screen
  name="Chat"
  component={Chat}
  listeners={{
    tabPress: e => {
      // Prevent default action
      e.preventDefault();
    },
  }}
/>

Here's the reference link to the docs: https://reactnavigation.org/docs/navigation-events/

Related