0

I'm building a React Native app using TabNavigator and StackNavigator.

  • I'm using TabNavigator at the root level of my React Native app.
  • Each route inside the TabNavigator maps to a StackNavigator.
  • Each StackNavigator has n number of screens.

Let's assume I'm on the Settings Tab and I'm 3 screens deep in user settings -> payment options -> credit card 1.

Each time I tap on the Settings Tab I want to go back one screen.

  • Tap 1: credit card 1 -> payment options
  • Tap 2: payment options -> user settings
  • Tap 3: user setting -> settings

How can I do this?

Derek Soike
  • 11,238
  • 3
  • 79
  • 74

1 Answers1

1

The key is dispatching the proper navigation action inside your route's tabBarOnPress method if your stack view's route index is not 0.

enter image description here


index.js

import React, { AppRegistry } from 'react-native'
import { Component } from 'react'
import MyTabNavigator from './components/MyTabNavigator'

class MyApp extends Component {
    render() {
        return (
            <MyTabNavigator/>
        );
    }
}

AppRegistry.registerComponent('MyApp', () => MyApp);

MyTabNavigator.js

import HomeStackNav from './HomeStackNav'
import SettingsStackNav from './SettingsStackNav'

const goBackNavigationAction = NavigationActions.navigate({
  action: NavigationActions.back()
})

const routeConfig = {
  Home: {
    screen: HomeStackNav,
    path: 'home',
    navigationOptions: {...}
  },
  Settings: {
    screen: SettingsStackNav,
    path: 'settings',
    navigationOptions: ({ navigation }) => ({
      title: 'settings',
      tabBarLabel: 'settings',
      tabBarOnPress: (scene, jumpToIndex) => {
        jumpToIndex(scene.index)
        if (scene.route.index > 0) {                  // <----- this is
          navigation.dispatch(goBackNavigationAction) // <----- where the
        }                                             // <----- magic happens
      }
    })
  }
}

const tabNavigatorConfig = {...}

export default TabNavigator(routeConfig, tabNavigatorConfig)
Derek Soike
  • 11,238
  • 3
  • 79
  • 74