Search code examples
react-nativereact-navigationtabnavigator

Set initialRouteName dynamically in React Navigation TabNavigator


I want to set initialRouteName of my TabNavigator dynamically in splash screen. In splash, i decide initialRouteName based on an api result but i don't know how to pass this route name to my router file.

Router.tsx:

public static Routes = StackNavigator({
    Splash: { screen: Splash },
    Verification: { screen: Verification },
    Login: { screen: Login },
    Main: {
        screen: TabNavigator({
            Calendar: { screen: Calendar },
            PendingReserves: { screen: PendingReserves },
            Profile: { screen: Profile },
        }, 
        {initialRouteName: 'Calendar'}) // I want to set it from splash
    }        
}, {initialRouteName: 'Splash'} );

splash.tsx:

constructor(props: SplashScreenProps, context: any) {
    super(props, context);
    this.state = {
        Error: false
    }
    this.check()
}

check = async () => {
    let pending = await dataService.getPendingReserves(data);
    if (pending.Success) {                
        if (pending.result.length > 0) {
            // go to pendingReserve Tab
        } else {
            // go to Calendar Tab
        }
    } else {
        this.setState({ Error: true })
    }
}

I tried to route statically to PendingReserves and in it's constructor, check the api and change tab if necessary but i couldn't change tab programmatically with this code:

pendingReserves.tsx:

fetchData = async () => {
    let res = await Utilities.getPendingReserves()
    if (res && res.length > 0) {
        ...
    } else {
        const resetAction = NavigationActions.reset({
            index: 0,
            actions: [NavigationActions.navigate({ routeName: 'Calendar' })]
        })
        this.props.navigation.dispatch(resetAction)
        // this.props.navigation.navigate({ routeName: 'Calendar' })
        // both reset and simple navigate are not works correctly... 
    }
}

So any solution for dynamically set initialRouteName OR change tab programmatically will help me. Thanks

I'm using:

"react-native": "0.49.3",
"react-navigation": "^1.0.0-beta.13"

Solution

  • Finally... I didn't find a way to change tab programmatically in react navigation version 1, so i update to version 2 and this.props.navigation.navigate('Calendar') works correctly.