Home > Blockchain >  How to navigate from Child Component to Parent in React Native
How to navigate from Child Component to Parent in React Native

Time:04-26

I have multiple Navigations nested together (Stacks and BottomTab) and i want to navigate from the child of a navigator to the top; consider the following example:

import { NavigationContainer } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/native-stack";

function AuthNav() {
  const Stack = createNativeStackNavigator();
  return (
    <NavigationContainer independent={true}>
      <Stack.Navigator>
        <Stack.Screen
          name="Signup"
          component={Signup}
          options={{ headerShown: false }}
        />
        <Stack.Screen
          name="Login"
          component={Login}
          options={{ headerShown: false }}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
} 

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen
          name="Auth"
          component={AuthNav}
          options={{ headerShown: false }}
        />
        <Stack.Screen name="Feed" component={Home} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

Say i want to move from my Signup screen back up to the App, and then navigate into the Home component, how would i go about doing that, also an explanation as to how the {independent: true} option works will be appreciated as well

CodePudding user response:

you are using the wrong formatting for coding

use this,

import { NavigationContainer } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/native-stack";

function AuthNav() {
  const Stack = createNativeStackNavigator();
  return (
    
      <Stack.Navigator>
        <Stack.Screen
          name="Signup"
          component={Signup}
          options={{ headerShown: false }}
        />
        <Stack.Screen
          name="Login"
          component={Login}
          options={{ headerShown: false }}
        />
      </Stack.Navigator>
    
  );
} 

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen
          name="Auth"
          component={AuthNav}
          options={{ headerShown: false }}
        />
        <Stack.Screen name="Feed" component={Home} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

I hope it resolves your issue.

CodePudding user response:

As mentioned in previous answer and comment, you're using NavigationContainer twice. You cannot do that. If you want to navigate back to parent screen, you can use navigation.goBack().

  • Related