For Navigation in React Native we have a library react-navigation
https://reactnavigation.org/docs/getting-started
Install library.
npm install @react-navigation/native
Install Dependencies
npx expo install react-native-screens react-native-safe-area-context
Wrap the whole app into Navigation Provider
/App.jsx
import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
export default function App() {
return (
<NavigationContainer>
</NavigationContainer>
);
}
Each new screen is placed on top of previous screens.
Mostly used when we require linear flow of application.
Example: List View
to Details View
to More Details View
.
We use Native Stack Navigator to use Navigation in more native way.
Install Native Navigator
npm install @react-navigation/native-stack
Import and instantiate the createNativeStackNavigator()
in App.js
/App.jsx
Create the screens
directory and place the screens that we have to render.
/screens/HomeScreen.jsx
/screens/ProfileScreen.jsx
Understanding the Stack.Screen
<Stack.Screen
name="Home" // this is the title you see on top of the screen
component={HomeScreen} // this is the component you render in this tab
/>
Understanding the <Stack.Navigator>
<NavigationContainer>
<Stack.Navigator
initialRouteName='Profile' // initially which screen should show
>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Profile" component={ProfileScreen} />
</Stack.Navigator>
</NavigationContainer>
We have two ways to navigate in StackNavigator
navigation
PropuseNavigation
HookWe use navigation prop methods for all the screens and useNavigation hook method for all other components.