Search code examples
reactjsreact-nativereact-navigationtabnavigator

Is there an onPress for TabNavigator tab in react-navigation?


I am trying to have a DrawerNavigator when user taps on the last tab(for example 'More') in TabNavigator.

How is this possible to achieve it without having a screen for that tab and then calling the DrawerNavigator in componentWillMount.

componentWillMount() {
   this.props.navigation.navigate("DrawerOpen") 
}

It is kind of a hack which is not proper solution I think(This way 'More' screen is loaded), there has to be a better solution for that.


Solution

  • This is also a bit of hack but I think its the simplest hack without using a custom TabBar or redux.

    What you can do is to create a screen component rendering null

    export default class More extends Component {
      render() {
        return null;
      }
    }
    

    Then add this screen to your TabNavigator, import TabBars from react-navigation and toggle drawer for certain index.

    import { TabBarBottom, TabBarTop } from 'react-navigation';
    
    const TabBar = Platform.OS === 'ios' ? TabBarBottom : TabBarTop;
    
    const Navigator = TabNavigator({
      Tab1: { screen: Tab1 },
      Tab2: { screen: Tab2 },
      Tab3: { screen: Tab3 },
      More: { screen: More }
    }, {
      tabBarComponent: ({jumpToIndex, ...props, navigation}) => (
            <TabBar
                {...props}
                jumpToIndex={index => {
                    if (index === 3) {
                        navigation.navigate('DrawerToggle'); //Toggle drawer
                    }
                    else {
                        jumpToIndex(index)
                    }
                }}
            />
        )
    });
    

    This way you simple continue using default TabBars from react-navigation, have an icon/label for your drawer and use it to toggle drawer.