Pass ref for dispatch in NavigationContainer in react-navigation v5

Viewed 746

Earlier I have been use createAppContainer in my navigation. Now while upgrading to react-navigation v5 i am not able to find a replacement for the dispatch reference passed. Sample code from react navigation given below:

const AppContainer = createAppContainer(AppNavigator);

class App extends React.Component {
  someEvent() {
    // call navigate for AppNavigator here:
    this.navigator &&
      this.navigator.dispatch(
        NavigationActions.navigate({ routeName: someRouteName })
      );
  }
  render() {
    return (
      <AppContainer
        ref={nav => {
          this.navigator = nav;
        }}
      />
    );
  }
}
1 Answers

According to the documentation, in version 5, screens are not accessed statically. That means only the sibling/parent/child screens are accessible directly, and for others you must specify the hierarchy for the navigator to find and access the nested screen.

This is how it works (also notice that routeName is now name and NavigationActions is now CommonActions and imported from @react-navigation/native) :

import {CommonActions} from '@react-navigation/native';

this.navigator.dispatch(
  CommonActions.navigate({name: someRouteName, //immediate screen to start with
                          params:{ screen: **the nested screen name** }
                         })
);

You may do this recursively, to gain access to deeper screens as well. For that to happen, just pass this object to the dispatch function:

//object to pass to CommonActions.navigate for dispatch:
{name: screen1Name, 
  params:{screen: screen2Name, 
    params:{screen: screen3Name, 
      params:{screen: screen4Name, 
        params:{screen: screen5Name
        }
      }
    }
  }
}

If you want to achieve the same goal with navigation.navigate, just add pass the name of the first screen as the first argument, and the object as the param. just like this

//2 arguments to pass into navigation.navigate:
(screen1Name, // <--- The first screen is given as a separate argument
  params:{screen: screen2Name, 
    params:{screen: screen3Name, 
      params:{screen: screen4Name, 
        params:{screen: screen5Name
        }
      }
    }
  )

Also remember, AppContainer is now NavigationContainer and is imported from @react-navigation/native

Related