React-Navigation: Navigate screen when Declared


    import React, { Component } from 'react';
    import MainNavigator from './src/navigation';
    import {connect} from 'react-redux';


    class Application extends Component {

      _checkToken(token){
        //TODO: Validate token!
         return true;
      }

      _isLoggedin(){
          if(this._checkToken(this.props.token)){
              MainNavigator.navigate('Home');
          }else{
              MainNavigator.navigate('Login');
          }
      }

      componentDidMount(){
        this._isLoggedin();
      }

      componentDidUpdate(){
          this._isLoggedin();
      }

      render() {
        return (
           MainNavigator 
        );
      }
    }

    const mapStateToProps = (state) => {
        return {token: state.auth.token};
    };

    export default connect(mapStateToProps)(Application);


    MainNavigator = SwitchNavigator({
        intro: {screen: introScreen},
        login: {screen: loginScreen},
        Home: {screen: homeScreen}
    });

I would like this component (Application) to be responsible for navigating the view to the correct screen depending on the authentication state that is retrieved from redux/redux-persist. I implemented this approach because I would like the user to be able to close the App without the need to log in again. Hence, when componentDidUpdate or componentDidMount is triggered I check the validity of the stored token and try to navigate based on that.

My issue is how do I navigate through MainNavigator 's Screens? The documentation addressed navigation by using this.props.navigation.navigate([ScreenName]) but I can't use this method here.

Thank you in advance!

1 answer

  • answered 2018-05-16 14:19 Marek N.

    You could create a NavigationService as described in the official documentation

    Just create a new NavigationService.js file.

    import { NavigationActions } from 'react-navigation';
    
    let _navigatorRef;
    
    function setNavigatorRef(navigatorRef) {
      _navigatorRef = navigatorRef;
    }
    
    function navigate(routeName, params) {
      _navigatorRef.dispatch(
        NavigationActions.navigate({
          routeName,
          params,
        })
      );
    }
    
    export default {
      navigate,
      setNavigatorRef,
    };
    

    In your top level component you can pass the Navigator to your service like this.

    import NavigationService from './NavigationService';
    
    const MyNavigator = createStackNavigator({ bla bla bla })
    
    class App extends React.Component {
      render() {
        return (
          <MyNavigator
            ref={navigatorRef => {
              NavigationService.setNavigatorRef(navigatorRef);
            }}
          />
        );
      }
    }
    

    Now you can use this service to navigate from your top level component (e.g App.js). Just use the function navigate().

    NavigationService.navigate('LastScreen');