Leonardo Drici
Leonardo Drici

Reputation: 789

React Navigation pass params to nested stackNavigator

In react navigation 3.0 they added the feature to pass default params to screen. The problem is that I want to pass those params to a nested stackNavigator but I can't figure out how to do so. These are my navigators: MainDrawer.js:

    const MyDrawerNavigator = createDrawerNavigator({
      Anime: {
        screen: SerieNavigation,
        params: { type: "anime" },
        path: "anime/:anime"
      },
      Tv: {
        screen: SerieNavigation,
        params: { type: "tv-show" },
        path: "tv/:tv"
      },
      Film: {
        screen: SerieNavigation,
        params: { type: "film" },
        path: "film/:film"
      }
    });

    const AppContainer = createAppContainer(MyDrawerNavigator);

    export default AppContainer;

SerieNavigation.js:

    const SerieStack = createStackNavigator(
      {
        Content: {
          screen: SearchScreen,
          params: { type: "anime" } //<-- HERE I WOULD LIKE TO DO SO params: { type: props.navigation.state.params.type }
        },
        Serie: SearieScreen,
        Episode: EpisodePage
      },
      {
        headerMode: "none",
        navigationOptions: {
          headerVisible: false
        }
      }
    );

    SerieStack.defaultNavigationOptions = {};
    export default SerieStack;

Any help is appreciated.

Upvotes: 9

Views: 11207

Answers (2)

Leonardo Drici
Leonardo Drici

Reputation: 789

To access props of the parent you can use this.props.navigation.dangerouslyGetParent().getParam('type'); now you can access any prop of the parent.

EDIT:

Not sure if this will work with react-navigation v5 but give it a try

Upvotes: 15

kivul
kivul

Reputation: 1158

I believe you could achieve that by passing your screenProps to your stackNavigator. Like this (assuming you return your stack navigator somewhere):

render() {
  <MyDrawerNavigator screenProps={this.props} />
}

Then, you can access it inside your SerieStack like this:

const SerieStack = createStackNavigator(
{
  Content: {
    screen: SearchScreen,
    params: { type: this.props.screenProps.navigation.state.params.type }
  }
});

Upvotes: 1

Related Questions