We can get access to a navigator through a ref and pass it to the NavigationService which we will use for navigate from anywhere . Use this only with the top-level (root) navigator of your app.

step 1: Create a file NavigationService.js

import { NavigationActions } from 'react-navigation';

let _navigator;

function setTopLevelNavigator(navigatorRef) {
  _navigator = navigatorRef;
}

function navigate(routeName, params) {
  _navigator.dispatch(
    NavigationActions.navigate({
      routeName,
      params,
    })
  );
}

// add other navigation functions that you need and export them

export default {
  navigate,
  setTopLevelNavigator,
};


step 2:  Add the navigation ref in app.js as below


import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { AppNavigator } from './navigator';
import NavigationService from './NavigationService';
import { store } from './redux/store';


class App extends Component {
   render() {
     return (
      
                  ref={navigatorRef => {
          NavigationService.setTopLevelNavigator(navigatorRef);
        }}
         />
      

     );
   }
}
export default App;

step 3 : To use of navigation ref , import  NavigationService and call the navigate function

import NavigationService from '../../NavigationService';
const checkAuth=(response)=>{
  if(response.status==='unauthorized'){
      NavigationService.navigate('Logout');
  }else {
    return true;
  }
}
export default checkAuth;


0 Comments

Leave a reply

Your email address will be private. Required fields are marked with *

Name *
Email *
Website