Search code examples
react-nativewix-react-native-navigation

React Native Navigation: Navigate to a screen from outside a React component


https://wix.github.io/react-native-navigation/docs/basic-navigation#navigating-in-a-stack indicates that pushing a new screen to the stack requires the current screen's componentId. My use case is to allow navigating based on certain events emitted by a native module. As such, componentId won't be available to me, since the event listener would reside outside any React component screen. Is there any way to navigate to a screen from outside in RNN? Or even get the current componentId.


Solution

  • I ended up adding a command event listener to store the current componentId in closure.

    let currentComponentId;
    
    Navigation.events().registerCommandListener((name, params) => {
      if (name === 'push') {
        currentComponentId = params.componentId;
      }
    });
    
    Navigation.events().registerAppLaunchedListener(() => {
      Navigation.setRoot(rootRouteConfig);
    
      EventEmitter.addListener('navigate', (name) => {
        Navigation.push(currentComponentId, {
          component: {
            name,
          },
        });
      });
    });