This tutorial series will help you decide and implement the navigation strategy for your need spanning across Stack Navigators, Drawer Navigator or Tab Navigator, or even nesting them, step by step.
Alternatively, you can opt to go through our Youtube playlist to get the same tutorial.
First things first, let’s get our hands dirty and install React Navigation 5.x:
npm install @react-navigation/native
npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view
Run them in your project directory, import the gesture handler in entry file of your app — App.js or index.js to avoid any crashes in release stage.
import 'react-native-gesture-handler'
The Stack Navigator
Well done! To get a handle on Stack Navigator, Let’s understand some common actions available with Stack Navigation:
push() — pop() — replace() — navigate() — popToTop()
push () — The
push
action adds a route on top of the stack and navigates forward to it.pop () — The
pop
action takes you back to a previous screen in the stack.replace () — The
replace
action allows to replace a route in the navigation statenavigate () — The
navigate
will pop back to earlier route in the stack if a route of the given name is already present therepopToTop () — The
popToTop
action takes you back to the first screen in the stack, dismissing all the others.
This article covers Stack Navigation, so let’s install the stack module below:
npm install @react-navigation/stack
Step 1:
We are now set to create our Stack Navigator. We will create three screens in a new screens folder. The actions we will perform is also shown below:
Splash.js -(replace)-> Login.js -(replace)-> Home.js
Lets create these screens with screen name, and most importantly, the action we will take, we include a button to trigger our action as shown :
Splash.js
Login.js
Home.js
Our project structure should look like this(of-course with other files and folders which we did not touch):
- screens/
- Home.js
- Login.js
- Splash.js
- App.js
Step 2 :
Next, we define the routing configurations in App.js
Step 2.1
Import create Stack Navigator:
import {createStackNavigator} from '@react-navigation/stack';
Create the Stack object from createStackNavigator
const Stack = createStackNavigator();
Step 2.2
Step 3:
Let’s test the app in device/emulator:
npx react-native run-android
Boom! Done!
Let us know if your app have a complex use of stack navigator and we would be happy to help.
Cheers!