Arun kumar
Arun kumar

Reputation: 1081

How to get previous route in react navigation?

I am user react navigation in react native application. After login I navigate to Home screen from where I want to sign out I should be navigate to previous screen(say Login). But inside navigation props I am unable to find any way to Login screen back without use of goBack function. My navigation is little messy please see my navigation carefuly.

This is my Navigators

import React from 'react';
import{ View, Text } from 'react-native';

// Navigators
import { DrawerNavigator, StackNavigator, TabNavigator } from 'react-navigation'

// Drawer Screens
import Welcome from '../../screens/Welcome';
import Profile from '../../screens/Profile';

// Tab Screens
import Home from '../../screens/Home';
import Message from '../../screens/Message';

//TabNav
const routeConfigs = {
    Home: {
        screen: Home,
        navigationOptions: {
          title: 'Home'
        }
    },
    Message: {
        screen: Message,
    },
}

const tabNavigatorConfig = {
    // tabBarComponent: tabBarComponent,
    tabBarPosition: 'top',
    lazy: true,
    tabBarOptions: {
        activeTintColor: 'yellow',
        inactiveTintColor: 'gray',
        style: {
            backgroundColor: '#8e24aa',
          },
        activeBackgroundColor: 'green',
    },
    header: 'screen'
}

export const TabNav = TabNavigator(routeConfigs, tabNavigatorConfig);

//Used Stack to get Header above TabBar
export const StackNav = StackNavigator({TabNav: { screen: TabNav }});

//DrawerNav 
export const DrawerNav = DrawerNavigator (
    {
        Welcome: { screen: Welcome},
        Profile: { screen: Profile },
        StackNav: { screen: StackNav}, // Stack Navigator to get Header on each Tabs
    },
    {
        initialRouteName: 'Welcome',
        drawerBackgroundColor: '#98eef3',
    }
);

This is Welcome or say Login Screen

import React, { Component } from 'react';
import { View, Text, StyleSheet, Button, TouchableOpacity, Modal, BackHandler, Alert, Image } from 'react-native';
import { connect } from 'react-redux';
import firebase from 'firebase';
import {
    loginUser
} from '../actions';
import Input from '../components/Input';
import Spinner from '../components/Spinner';

class Welcome extends Component {
    constructor(props){
        super(props);
        this.state = {
            modalVisible: false,
            email: '',
            password: '',
        }
        this.renderHome = this.renderHome.bind(this);
    }

    componentDidMount() {
        BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
    }

    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
      }

    handleBackButton = () => {
        Alert.alert(
            'Exit App',
            'Exiting the application?', 
            [
                {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'}, 
                {text: 'OK', onPress: () => BackHandler.exitApp()}
            ], 
            { cancelable: false }
        )
        return true;
    } 

    static navigationOptions = () => ({
        drawerLockMode: 'locked-closed'
    })

    loginButtonPress() {
        this.props.loginUser(this.state.email, this.state.password);
    }

    renderHome(){
        this.props.navigation.navigate('StackNav');
    }

    renderLoginButton(loading){
        if(loading){
            return <Spinner />;
        }else{
            return (
                <View style={{alignItems: 'center'}}>
                    <TouchableOpacity style={styles.button} onPress={this.loginButtonPress.bind(this)} >
                        <Text style={styles.buttonText}>Login</Text>
                    </TouchableOpacity>
                </View>
            );
        }
    }

    render() {
        return (
            <View style={styles.container}>
                {(this.props.user)?this.renderHome():null}
                <View style={{flex: 3, justifyContent: 'center'}}>
                    <Input
                        placeholder="Email"
                        keyboardType="email-address"
                        value={this.state.email}
                        onChangeText={(email) => this.setState({email})}
                    />
                    <Input
                        placeholder="Password"
                        value={this.state.password}
                        onChangeText={(password) => this.setState({password})}
                        secureTextEntry
                    />
                    {this.renderLoginButton(this.props.loading)}
        );
    }
}

mapStateToProp = ({auth}) => {
    return {
        user: auth.user,
        error: auth.error,
        loading: auth.loading,
    }
}

export default connect(mapStateToProp, { loginUser })(Welcome);

This is Home screen

import React, { Component } from 'react';
import { View, Text, Button, Alert, Animated, BackHandler } from 'react-native';
import { connect } from 'react-redux';
import Header from '../components/Header';
import Ionicons from 'react-native-vector-icons/Ionicons';
export class Home extends Component {

    constructor(props){
        super(props);
    }

    componentDidMount() {
        BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
    }

    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
      }

    handleBackButton = () => {
        Alert.alert(
            'Exit App',
            'Exiting the application?', 
            [
                {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'}, 
                {text: 'OK', onPress: () => BackHandler.exitApp()}
            ], 
            { cancelable: false }
        )
        return true;
    }
    
    static navigationOptions = ({navigation}) =>( {
        title: 'Home',
        header: <Header headerTitle={navigation.state.routeName}/>,
        headerTintColor: '#fff',
      });

    render(){
        console.log(this.props.user) // after signout getting undefined
        return (
            <View 
                style={{height: 1000}}
            >

                <View style={{height: 1000}}>
                  <Text>Home</Text>
                </View>
            </View>
        );
    }
}

mapStateToProp = ({auth}) => {
    return {
        user: auth.user,
    }
}

export default connect(mapStateToProp, null)(Home);

Signout is correctly working but need to navigate back to welcome/login screen.

Upvotes: 2

Views: 11657

Answers (2)

Shaksi
Shaksi

Reputation: 71

use a switch navigator - it is a screen that checks the users current status and forwards them to the appropriate screen.

  1. If user logs in, show user the Home screen
  2. If user logs out show user the Welcome screen
  3. If user arrives unauthenticated show user Welcome screen

update initialRouteName in the in your nav file and added AuthLoadingScreen.

import React from 'react';
import{ View, Text } from 'react-native';

// Navigators
import { DrawerNavigator, StackNavigator, TabNavigator } from 'react-navigation'

// Drawer Screens
import Welcome from '../../screens/Welcome';
import Profile from '../../screens/Profile';

// Tab Screens
import Home from '../../screens/Home';
import Message from '../../screens/Message';

import AuthLoadingScreen from '../../AuthLoading';

//TabNav
const routeConfigs = {
    Home: {
        screen: Home,
        navigationOptions: {
          title: 'Home'
        }
    },
    Message: {
        screen: Message,
    },
}

const tabNavigatorConfig = {
    // tabBarComponent: tabBarComponent,
    tabBarPosition: 'top',
    lazy: true,
    tabBarOptions: {
        activeTintColor: 'yellow',
        inactiveTintColor: 'gray',
        style: {
            backgroundColor: '#8e24aa',
          },
        activeBackgroundColor: 'green',
    },
    header: 'screen'
}

export const TabNav = TabNavigator(routeConfigs, tabNavigatorConfig);

//Used Stack to get Header above TabBar
export const StackNav = StackNavigator({TabNav: { screen: TabNav }});

//DrawerNav 
export const DrawerNav = DrawerNavigator (
    {
        Welcome: { screen: Welcome},
        Profile: { screen: Profile },
        Authloading: {screen: AuthLoadingScreen}
        StackNav: { screen: StackNav}, // Stack Navigator to get Header on each Tabs
    },
    {
        initialRouteName: 'AuthLoading',
        drawerBackgroundColor: '#98eef3',
    }
);

import React, { Component } from 'react';
import PropTypes from "prop-types";
import {
    ActivityIndicator,
    AsyncStorage,
    StatusBar,
    StyleSheet,
    View,
    Text
} from 'react-native';
import { connect } from 'react-redux'
import { withNavigation } from 'react-navigation'

class AuthLoadingScreen extends Component {
    static PropTypes = {
        navigation: PropTypes.object,
        isAuthenticated: PropTypes.bool
    }
    componentWillMount() {
        this._bootstrapAsync();
    }
    // Fetch the token from storage then navigate to our appropriate place
    _bootstrapAsync = () => {
        const userToken = this.props.isAuthenticated ? 'Tabs' : 'Onboarding';
        // This will switch to the App screen or Auth screen and this loading
        // screen will be unmounted and thrown away
        this.props.navigation.navigate(userToken);
    };

    // Render any loading content that you like here
    render() {
        return (
            <View style={styles.container}>
                <ActivityIndicator />
                <StatusBar barStyle="default" />
                <Text>hello</Text>
            </View>
        );
    }
}
const mapStateToProps = state => {
    return {
        isAuthenticated: state.auth || false,
    };
};
export default connect(mapStateToProps)(withNavigation(AuthLoadingScreen));

Upvotes: 1

tuan.tran
tuan.tran

Reputation: 1881

Instead of using goBack you can try Navigation.reset

    import { NavigationActions } from "react-navigation";
    ...
    export const logOut = navigation => {
      NavigationActions.reset({
        index: 0,
        actions: [NavigationActions.navigate({ routeName: "Welcome" })]
      })
    }

Upvotes: 1

Related Questions