Search code examples
iosreact-nativenavigationstack-navigator

StackNavigation how to know from which screen I navigated from?


I'm currently using a StackNavigator in my react native app.

I have two screens which both will navigate to the same screen LoginScreen. However, depending on which screen I came from, I'd like to go to different screens.

e.g:

ScreenA -> LoginScreen -> ScreenC

ScreenB -> LoginScreen -> ScreenD

As such in the LoginScreen I need to know which screen I've come from so that I know whether to go to screen C or D.

But the goBack function on the this.props.navigation is just a function that takes you back to the last screen. It doesn't give you the ID of the screen or some way of determining where you came from.

Does anyone have a solution to this?

Thanks


Solution

  • Login Screen would expect a flag, call it IsScreenA, this variable will come from Screen A and B as true orfalse respectively. Then, in Login Screen, navigate based on that flag:

    if(this.props.IsScreenA)
       this.props.navigation.navigate("ScreenC")
    else
       this.props.navigation.navigate("ScreenD")
    

    Now for the go back, use my answer here along with the above logic. You would call LoginScreen, and then based on whatever screen, you pass a different goBack().

    Edit:

    To pass a parameter, you do something like this:

    From Screen A:

    this.props.navigation.navigate("LoginScreen", {IsScreenA: true});
    

    From Screen B:

    this.props.navigation.navigate("LoginScreen", {IsScreenA: false});