I think this article captures the basic essence of navigation in react-native:
https://reactnative.dev/docs/navigation#usage
Here is an example:
Imagine this is my navigation tree:
StackNavigator
|- LoginScreen
|- HomeScreen
The StackNavigator would provide a nagivation prop to all its views. So you can use props.navigation anywhere in LoginScreen and HomeScreen. For instance, let's say we are at LoginScreen and want to navigate to HomeScreen
MainNavigator.js
const Stack = createStackNavigator();
const MyStack = () => {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="SignIn" component={SignInScreen} />
<Stack.Screen name="Home" component={HomeScreen} />
</Stack.Navigator>
</NavigationContainer>
);
};
SignInScreen.js
const SignInScreen = (props) => {
return (
<View>
<Button onPress={() => props.navigation.navigate('Home')}>
<Text>Go to Home Page</Text>
</Button>
</View>
);
};
So whenever you press the button on the SignInScreen, the navigator would do its magic and take you to the HomeScreen because we are calling props.navigator.navigate and providing it the name of the view we want to go to.
Architecture
From the architecture point of view, I would structure the above example as follow, basically structuring views based on the navigators:
src
|- navigators
|- MainNavigator
|- views
|- Main
|- SignInScreen
|- HomeScreen
Conditional Rendering and Nesting Navigators
A cool thing about navigators is that you can nest navigators and hide/show an entire flow based on some data. For example, you can hide AuthNavigator when user is logged in by conditionally render AuthNavigator based on auth status:
AppNavigator
|- AuthNavigator
|- SignUpScreen
|- SignInScreen
|- MainNavigator
|- HomeScreen
|- ProfileScreen
|- SomeOtherScreen
AuthNavigator.js
const AuthNavigator = () => {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="SignUp" component={SignInScreen} />
<Stack.Screen name="SignIn" component={SignUpScreen} />
</Stack.Navigator>
</NavigationContainer>
);
};
MainNavigator.js
const MainNavigator = () => {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Profile" component={ProfileScreen} />
<Stack.Screen name="SomeOther" component={SomeOtherScreen} />
</Stack.Navigator>
</NavigationContainer>
);
};
AppNavigator.js
const AppNavigator = () => {
const auth = true; // replace your logic here
return (
<NavigationContainer>
<Stack.Navigator>
{auth ?
<Stack.Screen name="Auth" component={AuthNavigator} /> :
<Stack.Screen name="Main" component={MainNavigator} />
}
</Stack.Navigator>
</NavigationContainer>
);
};
You can find more information about nesting navigators here: https://reactnavigation.org/docs/nesting-navigators/. In this example, their navigator structure is of the following:
AppNavigator
|- Home
|- Feed
|- Message
|- Profile
|- Settings
Feel free to let me know if you have any other questions :)