Natwar Singh
Natwar Singh

Reputation: 2273

How to set initial tab in react navigation TabNavigator dynamically

I am using react-navigation and have a nested TabNavigator inside a StackNavigator. I have three tabs in TabNavigator and need to set initialRouteName for TabNavigator dynamically based on some logic.

I have tried putting the TabNavigator inside a React Component with dynamically selected initial tab and used in StackNavigator with passing props through screenProps of TabNavigator. But this way I am unable to navigate to any route of StackNavigator.

Is there any way to make initialRouteName dynamically.

Note: I am not using redux for this application.

Upvotes: 10

Views: 8833

Answers (2)

hakki
hakki

Reputation: 6517

<Tab.Navigator
 initialRouteName="YOUR_TAB_NAME"
 ... 
/>

...

Reference:https://reactnavigation.org/docs/bottom-tab-navigator/#initialroutename

Full example:

const TabNavigator = createBottomTabNavigator();

function MyTabNavigator(props) {
  const { initialRouteName } = props;
  return (
    <TabNavigator.Navigator initialRouteName={initialRouteName}>
      <TabNavigator.Screen name="Tab1" component={Tab1} />
      <TabNavigator.Screen name="Tab2" component={Tab2} />
      <TabNavigator.Screen name="Tab3" component={Tab3} />
    </TabNavigator.Navigator>
  );
}

export default function App() {
  const initialRouteName = someCondition ? 'Tab1' : 'Tab2';
  return (
    <StackNavigator.Navigator>
      <StackNavigator.Screen
        name="TabNavigator"
        component={MyTabNavigator}
        initialParams={{ initialRouteName }}
      />
      <StackNavigator.Screen name="OtherScreen" component={OtherScreen} />
    </StackNavigator.Navigator>
  );
}

Upvotes: 12

foloinfo
foloinfo

Reputation: 693

It seems like you were really close.
You can set the index of navigation state to specify which to be shown as an initial route.

<SomeTabNavigator
  navigation={{
    ...this.props.navigation,
    state: {
      ...this.props.navigation.state,
      index: 1 // or whichever you want
    }
  }}
  screenProps={{
    // whatever the props you wanna pass to child screens.
  }}
/>

But you also have to pass the router via static otherwise you cannot navigate. (or try using navigate not push with navigation if you already have this.)

class Screen extends React.Component{

  static router = SomeTabNavigator.router

...

If this isn't the case then you should check the structure of your navigator that you have right nesting of stack navigator and tab navigator.

Maybe it's too late, but I hope it will help someone.

Check the link below for more details.

https://reactnavigation.org/docs/en/custom-navigators.html

Upvotes: 0

Related Questions