Stack-based Navigation

Learn how to navigate in React Native applications using a stack.

Stack-based navigation is the most basic form of navigation that can be added to React Native applications. Our entire application can be imagined as a stack; initially, we have the home screen on that stack. This home screen is the first screen that shows up when we launch the application. If we want to navigate to another screen, such as the dashboard, we will push that screen onto the stack. Now the dashboard will be the visible screen. Note that whatever screen is at the top of the stack will be the screen that is currently visible to the users. Similarly, if we want to go back to the home screen, we will just pop the dashboard screen from the stack so that the current screen on the top is the home screen. The illustration below shows how stack-based navigation works.

Press + to interact
Mobile application representing the behavior of stack-based navigation
Mobile application representing the behavior of stack-based navigation

Usage

To implement and use stack-based navigation, we first have to import NavigationContainer from the @react-navigation/native library.

Press + to interact
import { NavigationContainer } from '@react-navigation/native'

Next, we need to wrap our whole application inside the NavigationContainer using the <NavigationContainer></NavigationContainer> tag.

Press + to interact
import React from "react";
import { NavigationContainer } from '@react-navigation/native'
const App = () => {
return (
<NavigationContainer>
{/* Children components */}
</NavigationContainer>
);
};
export default App;

Now we have to import createNativeStackNavigator from the @react-navigation/native-stack library and use it to create a stack for navigation inside the application.

Press + to interact
import React from "react";
import { NavigationContainer } from '@react-navigation/native'
import { createNativeStackNavigator } from '@react-navigation/native-stack';
const Stack = createNativeStackNavigator();
const App = () => {
return (
<NavigationContainer>
{/* Children components */}
</NavigationContainer>
);
};
export default App;

Adding screen details

Once all the steps above have been completed successfully, we can use the Navigator and Screen methods of the created stack to add screen details. These screens will be pushed or popped from ...

Get hands-on with 1400+ tech skills courses.