🎉Celebrating 25 Years of Tech Excellence and Trust - Learn More

Getting Started with React Native Navigation: The Ultimate Guide+Tutorial

Updated : Aug 25, 2022
Guide to React Native Navigation
TezJS for Fastest Performance

Do you want to develop a pair of native and iOS apps that have almost 99% of code in common? It’s possible with React Native.

Beyond any doubt, it has emerged as the most preferred cross-platform app development framework among developers.

And one crucial part of building apps is the navigation functionality; for example, moving from one screen to another, listening to events, passing parameters, and so on. Achieving these features is also entirely doable with React navigation, the essence of which was not only the requirement of individual developers but a community as a whole.

Accordingly, the library went through huge transformations and became one of the greatest navigation solutions for React Native apps.

Today in this article, we want to celebrate this vision by decoding the basics of React Native navigation so that you can create a robust app without any trouble.

Keep reading!

On This Page
  1. Prerequisites
  2. Project Setup
  3. React Navigation Setup
  4. Navigate to Another Screen
  5. Navigate with Parameters
  6. Configure the Header
  7. Go Back to Previous Screen
  8. Final Notes

Prerequisites to Get Started with React Navigation

The very first step is to ensure the installation of both Node.js and NPM on your system. You can run the following command to check whether you have them installed or not:

node -v

npm -v

If not, you can just install Node.js, and NPM will automatically be installed along with it.

Now it’s time to install Expo’s CLI by calling this:

npm install -g expo-cli

In case you did not know, Expo is a set of tools that’s the easiest way to start working with React Native. It enables you to initiate a project without the need to install and configure Android Studio or Xcode so that you can write and develop React Native apps in minutes.

The installation of NodeJS and NPM will also help you setup an environment for the TezJS project and build the fastest website.

Setting Up a New React Native Project

The next step of navigation in React Native is to create a new project with the help of Expo.

expo init react-navigation-tutorial —npm

You will then have to choose the app type. Select ‘blank.’ Once it’s done, run the init command to install the dependencies you require.

After that, move to the directory of your React Native project with this command:

cd react-navigation-tutorial

Now it's about time to install the needed dependencies to use React navigation. Using Expo’s CLI, run the given command to install the building blocks libraries:

expo install react-native-screens react-native-safe-area-context

Next, you have to install the React Native stack navigator library with the following command:

npm install @react-navigation/native-stack

Once you complete all these steps, you will finally have all the libraries needed to get started with React Native navigation.

Lastly, if you want to have beautiful and attractive components in your app, you can install React Native Paper. Call the command:

npm install react-native-paper

Create Impressive, High-performance Apps for Your Business with React Native

Hire Developers

Time for React Navigation Setup

First of all, you need to build a stack navigator before you add routes to the app. This React Native stack navigator will help you create screens, manage navigation history, navigate between screens, present appropriate screens based on the routes taken, and more in React Native navigation.

In App.js, change your content as mentioned below:

import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { Provider as PaperProvider } from 'react-native-paper';
import HomeScreen from './screens/HomeScreen';

const Stack = createNativeStackNavigator()

export default function App() {
return (
<PaperProvider>
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
</Stack.Navigator>
</NavigationContainer>
</PaperProvider>
);
}

You will notice that at the top of components, you first have <PaperProvider> in the return value of App. The reason is to ensure all screens in your app have a common theme.

Comes next in line the <NavigationContainer> component. It contains the navigation state and manages the navigation tree. As a result, this component wraps stack navigators.

Inside <NavigationContainer>, you will find <Stack.Navigator>. You can use createNativeStackNavigator to create Stack. This particular functionality contains two distinct properties to return an object: Navigator and Screen. The prior one is a React component that wraps all the Screen components to help you manage route configurations.

Therefore, you will find one or more <Stack.Screen> components inside <Stack.Navigator>. You are going to have a <Stack.Screen> component for each route, leaving you only one component pointing to the Home route.

Note that a Screen component takes the name prop – the route’s name that you will use as a reference later on while navigating to the same route – and the component property required to render for the route.

At this stage, you will pass the HomeScreen component to the Home route. This means you must create it now.

First of all, you have to write the screens directory. Inside that, create a new file HomeScreen.js with the below-mentioned content:

import React from 'react';
import { ScrollView, StyleSheet } from 'react-native';
import { Button, Card } from 'react-native-paper';
import { DefaultTheme } from 'react-native-paper';

function HomeScreen () {
return (
<ScrollView style={styles.scrollView}>
<Card style={styles.card}>
<Card.Title title="Home Screen" />
</Card>
</ScrollView>
)
}

const styles = StyleSheet.create({
scrollView: {
backgroundColor: DefaultTheme.colors.background,
paddingTop: 10
},
card: {
width: '90%',
marginLeft: 'auto',
marginRight: 'auto'
}
});

export default HomeScreen

As a final result, you will be able to build a basic home screen. The screen will have a ScrollView component consisting of a Card component. The title will be - “Home Screen.”

Congratulations! You just developed your very first route with React Navigation stack.

Now it's time to test it!

Execute the command:

npm start

It will allow you to run the app on Expo Go on your smartphone. Use the Camera app on iOS or the Expo Go app on Android to scan the QR code.

Once the app starts running, you will notice the Home Screen as the only default route:

Home Screen Navigation

Let’s Navigate to Another Screen

Ready to learn how you can navigate from one screen to another? Let's go!

Just like the Home Screen, every screen inside the Stack Navigator will get a navigation prop that will enable users to navigate between multiple screens on your app.

So, let’s build the screen your users will navigate to.

Here's the content to create the file screens/BookScreen.js.

import React from 'react';
import { StyleSheet, View } from 'react-native';
import { Card } from 'react-native-paper';
import { DefaultTheme } from 'react-native-paper';

function BookScreen () {
return (
<View style={styles.container}>
<Card style={styles.card}>
<Card.Title title="This is Books Screen" />
</Card>
</View>
);
}

const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
backgroundColor: DefaultTheme.colors.background,
alignItems: 'center',
paddingTop: 10
},
card: {
width: '90%'
}
});

export default BookScreen;

This screen will be similar to HomeScreen, displaying a card with the title – “This is Books Screen”

Now for Book Screen, you need to add the new route in App.js right under the ‘Home’ route:

<Stack.Screen name="Book" component={BookScreen} />

Keep in mind that, at the start of App.js, you have to import the BookScreen component by running the following command:

import BookScreen from './screens/BookScreen';

Inside this stack navigator, you will be able to navigate to the ‘Book’ route. Interested to see how it works? You will just have to add a button in HomeScreen. That button will navigate to BookScreen once a user clicks it.

In HomeScreen, make sure to add the navigation prop to the below-mentioned function:

function HomeScreen ({ navigation })

Next you need to change the return value to this:

return ( <ScrollView style={styles.scrollView}>
<Card style={styles.card}>
<Card.Title title="Navigate to 'Book' Screen" />
<Card.Content>
<Button mode="contained" onPress={() => navigation.navigate('Book')}>
Navigate
</Button>
</Card.Content>
</Card>
</ScrollView>
)

The next step is to change the card’s title to “Navigate to ‘Book’ Screen”. Add a Button element inside the card content using onPress listener. Once a user clicks on the button, the listener will be implemented.

Now inside the listener, you need to use the navigation prop to navigate to the Book screen. Here, the method navigate will be highly useful to do this as it takes the route name for the navigation function.

At this stage of React navigation, you have to test the app. Once you run it, a new button on the Home screen will appear as follows:

Navigating Book Screen

Now click on the navigate button to navigate to the BookScreen.

Book Screen Navigation

Note that when you navigate to another screen, the back button in the navigation bar gets automatically added. This button will help users navigate to the last screen (in our case, it’s the Home screen).

Want to Build High-functioning Apps with Native Feel and Glimpse?

Talk to Experts

Navigating to another screen by passing parameters to it is a critical task in many scenarios. Here we will learn how to create an input that will enable your users to enter their names and display a new screen named NameScreen – greeting users with the names they have entered.

Let's start!

To hold the value of the input that you’re about to add in HomeScreen.js, add a new state variable like this:

const [name, setName] = useState('');

At the start of the file, make sure to add an import for useState:

import React, { useState } from 'react';

Below the existing component, add a new card one:

<Card style={styles.card}>
<Card.Title title="Navigate with Parameters" />
<Card.Content>
<TextInput mode="outlined" label="Name" value={name} onChangeText={(text) => setName(text)} style={styles.textInput} />
<Button mode="contained" disabled={name.length === 0} onPress={() => navigation.navigate('Name', { name })}>
Navigate
</Button>
</Card.Content>
</Card>

This new card contains a TextInput and has the value of the name state variable. You can change the value on the onChangeText event that runs with any change users make to the input text.

When the name state variable is empty, there’s a disabled button below the input. Adding an onPress event listener is also necessary that helps users navigate to the Name route.

Remember that you pass a second parameter to the same navigation.navigate method. This method receives the second parameter as a passing object of parameter. So, inside the object, you’re here passing the name variable.

Finally, change the styles object in the HomeScreen to the following content:

const styles = StyleSheet.create({
scrollView: {
backgroundColor: DefaultTheme.colors.background,
paddingTop: 10
},
card: {
width: '90%',
marginLeft: 'auto',
marginRight: 'auto',
marginBottom: 10
},
textInput: {
marginBottom: 10
}
});

Develop Natively Rendered Cross-Platform Apps with React Native Caliber

Let's Begin

With a few changes in the card property, this adds a new property to textInput.

Now let’s build the component for the ‘Name’ route - NameScreen.

For that, you need to use the below-mentioned content and create Screens/NameScreen.js:

import React from 'react';
import { StyleSheet, View } from 'react-native';
import { Card } from 'react-native-paper';
import { DefaultTheme } from 'react-native-paper';

function NameScreen ({ route }) {
const { name } = route.params;
return (
<View style={styles.container}>
<Card style={styles.card}>
<Card.Title title={`Hello, ${name}`} />
</Card>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
backgroundColor: DefaultTheme.colors.background,
alignItems: 'center',
paddingTop: 10
},
card: {
width: '90%'
}
});

export default NameScreen;

Although the screen is basically the same as BookScreen, the route prop has passed to the function at this stage of React navigation.

As discussed earlier, the navigation stack components navigation from one screen to another with the help of a navigation prop they receive. They get a route prop as well, allowing you to pass the parameters to the screen using route.params.

Accordingly, NameScreen offers you the value of the Name input in HomeScreen. It then will pass while navigating to the NameScreen and clicking the button with route.params:

const { name } = route.params;

Using the name parameter, you’ll be able to show users a greeting inside a card.

In the end, add the ‘Name’ route to the stack navigator by adding a new <Stack.Screen> under the former routes in App.js:

<Stack.Screen name="Name" component={NameScreen} />

And at the start of the file, import NameScreen under previous imports:

import NameScreen from './screens/NameScreen';

It's time to test it out! The homescreen will have a new card with a button and an input:

Name Screen Navigation

Now enter your name and click on the ‘Navigate’ button under the input. It will navigate you to the NameScreen and show your name.

Navigating Name Screen

The name in the NameScreen will change accordingly in case you need to go back and change the value of the name.

Header Configuration in React Navigation

Now let’s understand header configuration in react navigation.

1. Changing the Title

Let's learn how you can enter a title by adding a new input in HomeScreen. Once you click the navigate button, you’ll be able to navigate to a new screen – TitleScreen. Its title will change according to the title you enter in the input in HomeScreen.

To save the title, add a new state variable in HomeScreen.js.

const [title, setTitle] = useState('');

Under the previous cards, add a new one:

<Card style={styles.card}>
<Card.Title title="Navigate to Route with Title" />
<Card.Content>
<TextInput mode="outlined" label="Title" value={title} onChangeText={(text) => setTitle(text)} style={styles.textInput} />
<Button mode="contained" disabled={title.length === 0} onPress={() => navigation.navigate('Title', { title })}>
Navigate
</Button>
</Card.Content>
</Card>

Although this card is almost the same as the previous one, it uses the state variable title, and the onPress listener for the button navigates to the ‘Title’ route and passes the title as a parameter.

The next step is to create the screens/Title.js file with this content:

import React from 'react';
import { StyleSheet, View } from 'react-native';
import { Card } from 'react-native-paper';
import { DefaultTheme } from 'react-native-paper';

function TitleScreen () {
return (
<View style={styles.container}>
<Card style={styles.card}>
<Card.Title title="This is title screen" />
</Card>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
backgroundColor: DefaultTheme.colors.background,
alignItems: 'center',
paddingTop: 10
},
card: {
width: '90%'
}
});

export default TitleScreen;

With no specialty, this screen doesn’t even use the title parameter and only displays a card with the title - “This is title screen”. The reason is, while adding the route, you can pass an options parameter to <Stack.Screen> and change the title of the screen.

At the start of the file, add a new import for TitleScreen under previous imports:

import TitleScreen from './screens/TitleScreen';

After this, under the last <Stack.Screen>, add the new route:

<Stack.Screen name="Title" component={TitleScreen} options={({route}) => ({title: route.params.title})} />

Now every component in Stack.Screen is capable of taking an options prop which can be an object like this:

options={{title: "Hello"}}

If your options are static, this should be enough. And in case you’ve a dynamic value of any options, pass it a function to return an object. Such a function can receive values as a parameter route:

options={({route}) => ({title: route.params.title})}

This function allows you to return an object having a title property with route.params.title. As a result, you can pass the title to the route and change the title of ‘Title’ route by passing the function to the options prop.

Now you can test it. You will see the Home screen with a new card and a new input:

Title Screen Navigation

enter a title of your choice and click on the Navigate button. It will navigate you to the TitleScreen with the input value you’ve entered:

Navigation to Title Screen

2. Adding a Header Button

With React Native navigation, now you can add a header button and personalize what it displays on the right and left with the headerLeft and headerRight properties in the options parameter of <Stack.Screen>.

Let's try adding a right header button on the Home screen.

Add an options prop to the ‘Home’ in App.js:

<Stack.Screen name="Home" component={HomeScreen} options={{
headerRight: () => (
<IconButton icon="alert-outline" onPress={() => alert('You\'re awesome!')} color={DefaultTheme.colors.notification} />
)
}} />

Then, pass an object with the headerRight property in the options prop. This particular property is essentially a component that can be rendered inside; for example, you can render the IconButton having an icon without any text. Now show an alert to your users in the onPress event listener:

That’s it! Test the app and see that the Home screen has a new button at the top right corner of the header:

Header Navigation

You'll notice an alert on clicking the header button:

Header Button Navigation

Going Back to the Previous Screen in React Native Navigation

In this last section of navigation in React Native, you’ll learn to programmatically go back to the previous screen.

For that, you need to create the screens/BackScreen.js with this content:

import React from 'react';
import { StyleSheet, View } from 'react-native';
import { Button, Card } from 'react-native-paper';
import { DefaultTheme } from 'react-native-paper';

function BackScreen ({ navigation }) {
return (
<View style={styles.container}>
<Card style={styles.card}>
<Card.Title title="This is Back Screen" />
<Card.Content>
<Button mode="contained" onPress={() => navigation.goBack()}>
Go Back
</Button>
</Card.Content>
</Card>
</View>
);
}

const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
backgroundColor: DefaultTheme.colors.background,
alignItems: 'center',
paddingTop: 10
},
card: {
width: '90%'
}
});

export default BackScreen;

Here you will notice two things – firstly, the screen uses the navigation prop and passes it to the navigation stack components. Secondly, the screen contains a button inside a card, and if a user clicks on it, it will use the navigation prop and go back utilizing the goBack method:

<Button mode="contained" onPress={() => navigation.goBack()}>

After this, you need to go to the HomeScreen and add a new card at the bottom of the ScrollView:

<Card style={styles.card}>
<Card.Title title="Navigate to 'Back' Screen" />
<Card.Content>
<Button mode="contained" onPress={() => navigation.navigate('Back')}>
Navigate
</Button>
</Card.Content>
</Card>

This card only has a button to navigate to the ‘Back’ route. It's time to add that route.

Under the previous components, add a new <Stack.Screen> in App.js:

<Stack.Screen name="Back" component={BackScreen} />

It's now ready to be tested. Note that at the end of the list, you’ll have a new card:

It's now ready to be tested. Note that at the end of the list, you’ll have a new card:

Previous Screen Navigation

Now to navigate to the BackScreen, click on the ‘Navigate’ button:

You can go back to the HomeScreen by clicking on “Go Back” on the card.

Final Notes

We hope this article helps you kickstart your React Navigation journey in your current or upcoming React Native apps. This was merely a short introduction to this tutorial, and there’s still a lot you can achieve!

In the end, it will definitely fulfill most of your business and software needs!

And if you want to learn more, feel free to reach out to the seasoned React Native developers of Radixweb house. They will help you with more insights on React Native navigation and how you can build production-ready apps with it.

Till then, happy coding!

Don't Forget to share this post!

Vinit kariatukaran is a senior mobile application development manager at Radixweb and passionate about developing and designing innovative high-reach mobile applications. He endeavors to keep himself abreast of all the latest technological changes and updates to deliver the best in the business. When at leisure, he loves to read books and have interesting conversations with his colleagues and friends.