4

Imagine I have this structure for my tab bar:

const TabBarRoute = {
    Home: HomeStack,
    Orders: OrdersStack,
    Trending: TrendingStack,
    TopSelling: TopSellingStack
}

I want to show only three tabs (Orders, Trending, TopSelling) in my bottom tab navigator, How can I achieve it by react-navigation version 3.x ?

One idea that come to my mind is that I create a top stackNavigator and nest HomeStack along with my bottomTabNavigator inside of that and set the initial route of the top stackNavigator to the Home but problem with this approach is that it doesn't show the tab bar.

Rathma
  • 1,196
  • 2
  • 33
  • 65

2 Answers2

2

This example is using createBottomTabNavigator, but I imagine the same rules apply. It requires overriding the tabBarButtonComponent with a Custom component which returns null when the user doesn't have access to the given Tab.

const Config = {
    allow_locations: true,
    allow_stations: true
}

LocationsStackNavigator.navigationOptions = ({navigation}) => {
  return {
    tabBarLabel: 'Locations',
    tabBarTestID: 'locations',
    tabBarIcon: ({focused}) => (
      <TabBarIcon
        focused={focused}
        name={'md-settings'}/>
    )
  }
};

const MyTabNav = createBottomTabNavigator(
  {
    LocationStackNavigator,
    StationsStackNavigator,
    OrdersStackNavigator,
    SettingsStackNavigator
  },
  {
    defaultNavigationOptions: ({ navigation }) => ({
      tabBarButtonComponent: CustomTabButton
    })
  }
);


class CustomTabButton extends React.Component {
  render() {    
    const {
      onPress,
      onLongPress,
      testID,
      accessibilityLabel,
      ...props
    } = this.props;

    if(testID === 'locations' && !Config.allow_locations) return null;
    if(testID === 'stations' && !Config.allow_stations) return null;

    return <TouchableWithoutFeedback onPress={onPress} onLongPress={onLongPress} testID={testID} hitSlop={{ left: 15, right: 15, top: 5, bottom: 5 }} accessibilityLabel={accessibilityLabel}>
        <View {...props} />
      </TouchableWithoutFeedback>;
  }
}
0

if you want to have dynamic items which they can change according to your situation you can do it in 2 ways : first, you can declare a component as a parent of your react-navigation component then

  1. create a store for your items and set them as @observable and change them whenever you want

  2. declare your items as a state of your parent component and pass them to your react navigation

In these two solutions, every time your items change caused your component re-render with new values

  • 1
    so how can I apply it in the context of `react-navigation` ? – Rathma Dec 04 '18 at 11:20
  • you can do it like this. class HomeScreen extends React.Component { render() { return ( Home Screen ); } } const RootStack = createStackNavigator( { Home:this.state.homeVisible ? HomeScreen :
    , Details: DetailsScreen, }, { initialRouteName: 'Home', } );
    – Alireza Yadegari Dec 04 '18 at 12:11