Maks Novikov
Maks Novikov

Reputation: 31

How to pass props from TabNavigator to StackNavigator in react native?

There are 2 StackNavigator objects with few screens inside a TabNavigator. How to pass props from App.js -> TabNavigator -> each StackNavigator -> screen?

Code below generates errors, saying that only one router can be rendered.

const SettingsStack = createStackNavigator({
  Settings: {screen: props => <SettingsScreen {...props} screenProps={{is_authenticated: props.is_authenticated}}/> },
  Profile: {screen: ProfileScreen},
});

const MainTabNavigator = createBottomTabNavigator({
    SettingsStack: {screen: props => <SettingsStack {...props} screenProps={{is_authenticated: props.is_authenticated}}/>},
})

Upvotes: 2

Views: 2189

Answers (2)

Maks Novikov
Maks Novikov

Reputation: 31

The solution I ended up with was removing all props-passing techniques and using screenProps. It turned out that when you have hierarchy such as AppComponent -> TabNavigator -> StackNavigator -> HomeComponent, where "->" means "includes" or "renders", there is no need to pass screenProps from TabNavigator to StackNavigator explicitly, because screenProps are passed within 2 navigators by default.

Upvotes: 1

Noah Allen
Noah Allen

Reputation: 796

You have to somehow provide a way to pass in properties into the navigator object. Perhaps your function could work like this:

function createNav (props) {
  // Do something
  return createStackNavigator({
    Settings: {screen: <SettingsScreen {...props})
  })
}

In your example, the you have screen as a function passing props to the component. But how does it know where to get those props from?

Another very straightforward option for basic props would be to pass a property with navigation. In this case, you basically call navigate('screen', {property: 'value'}) during navigation and then use

const val = navigation.getParam('property', 'defaultValue') // 'value'

to get it out in the screen you are navigating to.

Upvotes: 1

Related Questions