Search code examples
react-nativereact-native-tabnavigator

React Native Tab navigation from a button group


In React Native, I have a button group that I want controlling some tabs using Tab Navigation.

The tab pages all have tabBarVisible: false and I want to move to the correct tab page by calling navigate('screen1') etc. But inside my updateTab called from the button group's onpress I cannot access the navigation.navigate function.

What can I do?

import { TabNavigator } from 'react-navigation';

const Tabpage = TabNavigator(
{
   tab1: {
     screen: screen1,
     navigationOptions: {
     tabBarVisible: false,
     tabBarLabel: 'Screen 1'
  }, ...
}

export default class Tab extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tabIndex: 2
    };
    this.updateTabIndex = this.updateTabIndex.bind(this);
  }

   updateTabIndex = tabIndex => {
     console.log(tabIndex);
     this.setState({ tabIndex });
     switch (tabIndex) {
        case 0:
           console.log('nearby chosen');
           // navigate('screen1'); // error:  no function named navigate
           // navigation.navigate('screen1'); // error: not a function
           // this.navigate or this.navigation.navigate all fail too  
           break;
       case 1: // etc.
       default: // etc. 
     }
  }   

  render() {
    <View style={styles.tabsview}>
      <ButtonGroup
        containerBorderRadius={40}
        selectedBackgroundColor='#FF0000'
        onPress={ this.updateTabIndex }
        selectedIndex={this.state.tabIndex}
        buttons={['screen0', 'screen1', 'screen2']}
        containerStyle={{ height: 30 }}
      />
    </View>

How do I access the navigation from the changed state tab index?


Solution

  • Use this.props.navigation.navigate('screen1');