Home > Mobile >  Navigate to another StackNavigtor screen on button press React Native
Navigate to another StackNavigtor screen on button press React Native

Time:10-22

I have made a Main Navigator in which I have made 2 sub navigators: This is my MainNavigator:

import React, {useEffect, useState} from 'react';
import {createStackNavigator} from '@react-navigation/stack';
import storage from '../services/storage';
import {useDispatch, useSelector} from 'react-redux';
import {setUser} from '../store/reducers/auth';
import AuthNavigation from './AuthNavigation';
import MainNavigation from './MainNavigation';

const {Navigator, Screen} = createStackNavigator();

const StackNavigation = () => {
  const [isLogged, setIsLogged] = useState(false);
  const dispatch = useDispatch();
  const loadUser = async () => {
    try {
      const data = await storage.get('USER');
      if (data !== null && data !== '') {
        console.log('Hello user', data);
        dispatch(setUser(data));
        setIsLogged(true);
      }
    } catch (error) {
      console.log('APP JS ERROR', error.message);
    }
  };

  useEffect(() => {
    loadUser();
  }, []);

  return (
    <Navigator screenOptions={{headerShown: false}}>
      {isLogged ? (
        <Screen name="MainNavigation" component={MainNavigation} />
      ) : (
        <Screen name="AuthNavigation" component={AuthNavigation} />
      )}
    </Navigator>
  );
};

export default StackNavigation;

These are my sub navigators:

AuthNavigation:

import React from 'react';
import {createStackNavigator} from '@react-navigation/stack';
import SignUpScreen from '../screens/AccountScreens/SignUpScreen';
import LoginScreen from '../screens/AccountScreens/LoginScreen';
import ForgotPassword from '../screens/AccountScreens/ForgotPassword';
import OTPVerification from '../screens/AccountScreens/OTPVerification';
import SetNewPassword from '../screens/AccountScreens/SetNewPassword';

const {Navigator, Screen} = createStackNavigator();

const AuthNavigation = () => {
  const verticalAnimation = {
    gestureDirection: 'vertical',
    cardStyleInterpolator: ({current, layouts}) => {
      return {
        cardStyle: {
          transform: [
            {
              translateY: current.progress.interpolate({
                inputRange: [0, 1],
                outputRange: [layouts.screen.height, 0],
              }),
            },
          ],
        },
      };
    },
  };
  return (
    <Navigator
      initialRouteName={'Login'}
      screenOptions={{headerShown: false, animationEnabled: true}}>
      <Screen
        name="SignUp"
        component={SignUpScreen}
        options={verticalAnimation}
      />
      <Screen name="Login" component={LoginScreen} />
      <Screen name="ForgotPassword" component={ForgotPassword} />
      <Screen name="OTPVerification" component={OTPVerification} />
      <Screen name="SetNewPassword" component={SetNewPassword} />
    </Navigator>
  );
};

export default AuthNavigation;

MainNavigation:

import React, {useState} from 'react';
import {createStackNavigator} from '@react-navigation/stack';
import MyTabNavigation from './MyTabNavigation';
import GymDetailScreen from '../screens/InnerScreens/GymDetailScreen';
import AccountOverview from '../screens/DrawerScreens/AccountOverview';
import SubscriptionDetails from '../screens/DrawerScreens/SubscriptionDetails';
import BillingDetails from '../screens/DrawerScreens/BillingDetails';
import ChangePassword from '../screens/DrawerScreens/ChangePassword';
import BuySubscribtion from '../screens/InnerScreens/BuySubscribtion';
import ScanScreen from '../screens/InnerScreens/ScanScreen';
import PaymentSummary from '../screens/InnerScreens/PaymentSummary';
import PaymentMethod from '../screens/InnerScreens/PaymentMethod';

const {Navigator, Screen} = createStackNavigator();

const MainNavigation = () => {
  const horizontalAnimation = {
    cardStyleInterpolator: ({current, layouts}) => {
      return {
        cardStyle: {
          transform: [
            {
              translateX: current.progress.interpolate({
                inputRange: [0, 1],
                outputRange: [layouts.screen.width, 0],
              }),
            },
          ],
        },
      };
    },
  };
  return (
    <Navigator
      initialRouteName={'MyTabNavigation'}
      screenOptions={{headerShown: false, animationEnabled: true}}>
      <Screen name="GymDetailScreen" component={GymDetailScreen} />
      <Screen
        name="MyTabNavigation"
        component={MyTabNavigation}
        options={horizontalAnimation}
      />
      <Screen name="AccountOverview" component={AccountOverview} />
      <Screen name="SubscriptionDetails" component={SubscriptionDetails} />
      <Screen name="BillingDetails" component={BillingDetails} />
      <Screen name="ChangePassword" component={ChangePassword} />
      <Screen name="BuySubscription" component={BuySubscribtion} />
      <Screen name="ScanScreen" component={ScanScreen} />
      <Screen name="PaymentSummary" component={PaymentSummary} />
      <Screen name="PaymentMethod" component={PaymentMethod} />
    </Navigator>
  );
};

export default MainNavigation;

I want to go to MainNavigator on Login which is in AuthNavigator, Here is how I am doing this:

navigation.navigate('MainNavigation');

But its giving me this error:

The action 'NAVIGATE' with payload {"name":"MainNavigation"} was not handled by any navigator.

Do you have a screen named 'MainNavigation'?

If you're trying to navigate to a screen in a nested navigator, see https://reactnavigation.org/docs/nesting-navigators#navigating-to-a-screen-in-a-nested-navigator.

This is a development-only warning and won't be shown in production.

Please help me with this coz I am trying this for the first time. Thanks in advance

CodePudding user response:

You are using Authentication flows stated in React Navigation documents.

Please be noted that this approach using conditionally rendering screens which means screen is not rendered if condition is not fulfilled. So, application will cause error for navigation to non-existing screen.

What you need to do in order to jump to MainNavigation screen, is to set your isLogged variable in MainNavigator to true.

CodePudding user response:

navigation.navigate('MainNavigation'); Here you can not use navigate method because both are different Navigators

So you have to render your navigator on a Conditional base.

For ex:

you can save authTocken after Successful Login and in your main Route file you can check write condition whether authTocken is null or not. On that basis you can render your navigator Like,

 {
      authTocken != '' (
        <Stack.Navigator screenOptions={{ headerShown: false }} initialRouteName={initialRoute}>
          <Stack.Screen name={routes.Dasboard} component={Dashboard} />
          <Stack.Screen name={routes.Setting} component={Setting} />
        </Stack.Navigator>
      )
    :
       <Stack.Navigator screenOptions={{ headerShown: false }} 
         initialRouteName={initialRoute}>
          <Stack.Screen name={routes.Login} component={Login} />
          <Stack.Screen name={routes.Registration} component=Registration} />
        </Stack.Navigator>
  }
  • Related