Jamie Birch
Jamie Birch

Reputation: 6112

Navigate straight to the bottom screen of a StackNavigator whilst providing params for the intermediate screens

Background

I have an app with two StackNavigators: the LoginStack, and the MainStack. Upon the user completing login in the LoginStack, I navigate them to the next stack: MainStack.

If it's their first time using the app, the screen I navigate them to is MenuScreen (where they can navigate onward to VideoScreen by selecting a video); but if they've selected a video from the MenuScreen before, I skip past MenuScreen and navigate them directly to VideoScreen.

When skipping directly to VideoScreen, however, I find that upon calling navigation.goBack() from VideoScreen, MenuScreen is navigated back to without any navigation params. How can I ensure that these params are provided?

AppNavigator

const LoginStack = createStackNavigator({ LoginScreen });
const MainStack = createStackNavigator({
    MenuScreen,
    VideoScreen,
});

const AppNavigator = createSwitchNavigator(
    {
        LoginStack,
        MainStack,
    },
    {
        initialRouteName: "LoginStack",
    }
);

Routing from LoginStack's LoginScreen to MainStack's VideoScreen

const videoScreenParams = {
    originStack: "LoginStack",
    originScreen: "LoginScreen"
};

/* Called from the InitStack.
 * First we navigate to the MainStack, then we perform a sub-action
 * to navigate to the VideoScreen within that stack. */
this.props.navigation.navigate({
    routeName: "MainStack",
    params: {},
    action: {
        type: "Navigation/NAVIGATE",
        routeName: "VideoScreen",
        params: {
            videoScreenParams
        },
    },
});

Going back in MainStack from VideoScreen to MenuScreen

/* Called from VideoScreen. */
this.props.navigation.goBack();

The problem: When VideoScreen renders, navigation.state.params is undefined because we never navigated to it explicitly.

Note that navigation.state.params is correctly populated if we navigate to MenuScreen before navigating to VideoScreen (i.e. if we don't skip the intermediate screen).

Full reproduction

I've produced an Expo Snack as a minimal reproduction.

Upvotes: 0

Views: 41

Answers (1)

Jamie Birch
Jamie Birch

Reputation: 6112

Official response from Brent Vatne (a Member of the React Navigation organisation):

you would have to customize the router for this: API docs – Custom Routers

an example of how to do this kind of customization (implementing the actual behavior is up to you though): Excerpt from Brent's React Europe 2019 GitHub repo

So it looks like I have some further reading to do before implementing a solution. I'll update this answer with a concrete solution once I've come back to working on this and have solved it.

Upvotes: 0

Related Questions