react-nativereact-navigationex-navigation

In react-navigation what's the difference between routeName and key?


One thing that's a bit confusing is the difference between route name and key and why you would use one vs the other. And, how duplicate route names are handled.

This documentation says that you use routeName to navigate to a screen, and that key is "a unique identifier used to sort routes." What does that mean?

It seems like the route name doesn't have to be unique as shown in my example since both the outer tab and the inner stack have the same route name. When you use the navigate functions - you pass the route name, correct? If so how does it differentiate between the duplicate route names in nested navigators and when would you use the key instead?

        export TabsNavigator = TabNavigator({
          Home: {
            screen:StackNavigator({
              Home: { screen: HomeScreen },
            }),
          },
          Profile: {
            screen: StackNavigator({
              Profile: { ProfileScreen },
            }),
          },
        });

The documentation has an example of setting the key but I can't understand the context of what it's trying to do, or why you would do it in a real use case.

import { NavigationActions } from 'react-navigation'

const setParamsAction = NavigationActions.setParams({
  params: {}, // these are the new params that will be merged into the existing route params
  // The key of the route that should get the new params
  key: 'screen-123',
})
this.props.navigation.dispatch(setParamsAction)

Solution

  • You use the name of a screen specified in a Navigator (e.g. StackNavigator) to open / show a screen. Each screen has a unique identifier, which is the key. E.g. if you open two screens of the same type, they will have the same route name, but a different key.

    With this.props.navigation.dispatch(NavigationActions.setParams(params: {val: 'val'}, key: 'home-1')); you can update the navigation state of screen with key 'home-1'. E.g. if you have a StackNavigator and a settings screen on top of home screen you can update navigation state (this.props.navigation.state.params) of home screen from settings screen.