Navigation: Moving Between Screens

8 min read

Course: React Native

Topic: Navigation: Moving Between Screens 🗺️

Hey there, future React Native wizards! Welcome to one of the most crucial parts of building any mobile app: navigation. Let's be real, an app with only one screen is like a book with only one page. Not very exciting, right? Today, we're going to learn how to build the hallways, doors, and staircases of your app so users can move around freely.


1. React Navigation Basics: The Map of Your App

The Definition: In the world of mobile apps, "navigation" is the system that lets users move between different screens or sections.

The Problem: You've built a beautiful "Home" screen and an amazing "Profile" screen. They exist as separate components, but how do you make a button on the "Home" screen actually take the user to the "Profile" screen? Your app components are like isolated islands; we need to build bridges between them.

The Solution: Enter React Navigation! 🦸‍♂️ It's the most popular and widely-used library for handling navigation in React Native apps. Think of it as the GPS or map for your application. It helps define the paths users can take and always knows where the user is currently located.

Getting Started: The Foundation

Before we build any roads, we need to lay the foundation. React Navigation requires a few core packages to get started. Let's get them installed.

Installation ⚙️

First, install the main package:

bash
npm install @react-navigation/native

Next, we need the dependencies that do the heavy lifting behind the scenes.

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

A Quick Peek Under the Hood: What are these? react-native-screens uses the native navigation components of iOS and Android, which makes screen transitions super smooth. react-native-safe-area-context helps you position your content correctly, avoiding pesky notches and status bars at the top of the phone.

With our foundation in place, every app using React Navigation must wrap the entire structure in a NavigationContainer. This component is like the master map that holds all your routes and navigation state.

javascript
// App.js
import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';

export default function App() {
  return (
    <NavigationContainer>
      {/* Our Navigators and Screens will go here! */}
    </NavigationContainer>
  );
}

2. Stack Navigator: Pushing and Popping Screens 📚

The Definition: A Stack Navigator manages your screens like a stack of cards. When you visit a new screen, you place a new card on top of the stack. When you go back, you take the top card off to reveal the one below it.

The Problem: Think about a settings menu. You tap "Profile," then "Edit Email," then "Change Password." You expect the back button to take you from "Change Password" back to "Edit Email," and then back to "Profile." How do we manage this history of screens?

The Solution: The Stack Navigator is designed for exactly this! It provides a way for your app to transition between screens and manage a navigation history. It's the most common type of navigator.

Installation ⚙️

You need to add the stack navigator package to your project:

bash
npm install @react-navigation/stack

And one more tool to make it work with native gestures:

bash
npx expo install react-native-gesture-handler

Let's Build a Stack!

Imagine our app has two screens: a HomeScreen with a list of contacts and a ProfileScreen to view a specific contact's details.

javascript
// App.js
import * as React from 'react';
import { View, Text, Button } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

// A simple component for our Home screen
function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      <Button
        title="Go to Jane's Profile"
        onPress={() => navigation.navigate('Profile')} // This is how we move to another screen!
      />
    </View>
  );
}

// A simple component for our Profile screen
function ProfileScreen() {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>This is Jane's Profile</Text>
    </View>
  );
}

const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Profile" component={ProfileScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

Breakdown of the Magic ✨:

  • createStackNavigator(): This function gives us an object containing two components: Stack.Navigator and Stack.Screen.
  • Stack.Navigator: This is the wrapper for our stack. We can set an initialRouteName to tell the stack which screen to show first.
  • Stack.Screen: Each of these components defines a single route in our stack. The name prop is the unique identifier for the screen, and the component prop is the actual React component to render.
  • navigation.navigate('Profile'): The HomeScreen component automatically receives a navigation prop. This prop is our remote control for moving between screens. The .navigate() function says, "take me to the screen named 'Profile'."

Fun Fact: If you call navigation.navigate('Home') while you are already on the Home screen, absolutely nothing will happen. React Navigation is smart enough not to add the same screen to the top of the stack twice! If you ever need to, you can use navigation.push('Home'), which will always add a new screen to the stack.


3. Tab Navigator: Bottom Tabs for Easy Access 📑

The Definition: A Tab Navigator displays a bar of tabs, usually at the bottom of the screen, that allows the user to switch between different main sections of your app.

The Problem: Many apps (like Instagram, Twitter, or your phone's contact list) have a few core sections that users need to access from anywhere. A stack navigator isn't great for this because you'd have to keep going "back" to the home screen to switch sections. We need a persistent menu.

The Solution: The Tab Navigator is perfect for this. It keeps the main navigation options visible at all times, making it easy for users to hop between features.

Installation ⚙️

Time for another package! This one is for the bottom tabs.

bash
npm install @react-navigation/bottom-tabs

Let's Build Some Tabs!

Let's create an app with a FeedScreen and a MessagesScreen.

javascript
// App.js
import * as React from 'react';
import { View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';

function FeedScreen() {
  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>Your Feed!</Text>
    </View>
  );
}

function MessagesScreen() {
  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>Your Messages!</Text>
    </View>
  );
}

const Tab = createBottomTabNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Tab.Navigator>
        <Tab.Screen name="Feed" component={FeedScreen} />
        <Tab.Screen name="Messages" component={MessagesScreen} />
      </Tab.Navigator>
    </NavigationContainer>
  );
}

Breakdown of the Magic ✨:

  • createBottomTabNavigator(): Just like the stack navigator, this function gives us the Tab.Navigator and Tab.Screen components.
  • The structure is almost identical! You just wrap your Tab.Screen components inside a Tab.Navigator. React Navigation takes care of rendering the tab bar at the bottom and handling the switching logic.
  • You can customize the icons, labels, and colors of the tabs extensively through the options prop on each Tab.Screen.

4. Passing Parameters Between Routes ✉️

The Definition: Passing parameters means sending data from one screen to another when you navigate.

The Problem: In our first Stack Navigator example, we went to "Jane's Profile." But what if we had a list of 100 contacts? We need a way to tell the ProfileScreen which user's profile to display. We can't create 100 different profile screens!

The Solution: We can pass parameters, like a user ID, along with the navigate action. The destination screen can then read these parameters and display the correct information.

Analogy Time: Think of it like mailing a package. navigation.navigate() is the act of sending the package. The name of the screen is the address ('Profile'). The parameters are the contents inside the package ({ userId: 8675309, name: 'Jenny' }). The destination screen receives this package and can open it to see what's inside.

Let's Pass Some Data!

We'll modify our Stack Navigator example. The HomeScreen will now have two buttons to go to two different profiles.

javascript
// App.js
import * as React from 'react';
import { View, Text, Button } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

// HomeScreen now passes parameters
function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      <Button
        title="Go to Jane's Profile"
        onPress={() => navigation.navigate('Profile', { userId: 1, userName: 'Jane' })}
      />
      <Button
        title="Go to John's Profile"
        onPress={() => navigation.navigate('Profile', { userId: 2, userName: 'John' })}
      />
    </View>
  );
}

// ProfileScreen now receives and uses the parameters
function ProfileScreen({ route, navigation }) {
  // We get the params from the `route` prop!
  const { userId, userName } = route.params;

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>This is the profile of {userName}</Text>
      <Text>User ID: {userId}</Text>
    </View>
  );
}

const Stack = createStackNavigator();

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

export default App;

Breakdown of the Magic ✨:

  1. Sending Data: In HomeScreen, the navigate function now has a second argument: an object containing the data we want to send. navigation.navigate('Profile', { userId: 1, userName: 'Jane' }).
  2. Receiving Data: The ProfileScreen component receives a route prop in addition to the navigation prop. This route prop holds information about the current route, and most importantly, route.params contains the parameters that were passed to it.
  3. Using Data: We can then destructure the userId and userName from route.params and use them to render dynamic content!

And that's it! You now know the fundamental patterns for creating navigation in a React Native app. You can build stacks for step-by-step flows, tabs for main sections, and pass data between them to create a dynamic and interactive user experience. Happy coding! 🚀


Further Reading & References

Challenge

You are tasked with building a nested navigation structure for a mobile app using React Navigation. The app will have a main bottom tab bar, and one of those tabs will contain its own stack of screens.

Requirements:

  1. Wrap the entire application in a NavigationContainer.
  2. Create a root TabNavigator using createBottomTabNavigator with two tabs:
    • A 'Home' tab.
    • A 'Settings' tab that renders the SettingsScreen component.
  3. The 'Home' tab must render a nested StackNavigator as its component.
  4. This StackNavigator (created with createStackNavigator) should manage two screens:
    • A 'HomeFeed' screen, which will be the initial screen for this stack.
    • A 'Details' screen.
  5. In the HomeFeedScreen component, add a Button that navigates to the 'Details' screen.
  6. When triggering the navigation to 'Details', you must pass an object with the following parameters: itemId with a value of 86, and otherParam with a value of 'React Navigation is powerful'.
  7. Modify the DetailsScreen component to access these parameters via its route.params prop and display their values inside <Text> components.

Expected result

Your final code should correctly implement a nested navigation structure.

  • The App component must render a NavigationContainer wrapping a Tab.Navigator.
  • The Tab.Navigator should contain two Tab.Screen components, one for the 'Home' stack and one for the 'Settings' screen.
  • The component for the 'Home' tab's screen must be the HomeStackNavigator function you created.
  • The HomeStackNavigator function must return a Stack.Navigator containing Stack.Screens for 'HomeFeed' and 'Details'.
  • The Button inside HomeFeedScreen must call navigation.navigate('Details', { itemId: 86, otherParam: 'React Navigation is powerful' }) in its onPress prop.
  • The DetailsScreen must successfully destructure itemId and otherParam from route.params and render their values.
jsx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.