Day 3: Adding Navigation Between Screens Using React Navigation


In this tutorial, we’ll dive into how to navigate between different screens in your mobile app using React Navigation. By the end of today’s lesson, your app will support multiple screens, allowing users to move between them seamlessly. We’ll continue from where we left off in Day 2 and add new functionality.


What You Will Learn Today:

  1. Installing and setting up react-navigation
  2. Creating multiple screens
  3. Navigating between screens using a stack navigator
  4. Passing data between screens

Step 1: Install React Navigation

To add navigation to our app, we’ll use the popular library React Navigation. Let’s install the necessary packages.

  1. Open your terminal in your project directory.
  2. Run the following commands to install the core navigation library and the dependencies for stack navigation (which will allow us to navigate between different screens).
npm install @react-navigation/native
npm install @react-navigation/stack
npm install react-native-screens react-native-safe-area-context
  1. After installation, you’ll need to wrap your app in a navigation container. This is necessary to manage the navigation state of the app.

Step 2: Set Up Navigation in the App

Now, we’ll set up a basic navigation flow in our App.js. Replace the contents of App.js with the following code to configure navigation between a HomeScreen and a DetailsScreen.

import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import HomeScreen from './screens/HomeScreen';
import DetailsScreen from './screens/DetailsScreen';

const Stack = createStackNavigator();

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

Explanation:

  • NavigationContainer: The root component that holds the navigation state of your app.
  • createStackNavigator: A function that creates a stack of screens and provides navigation between them.
  • Stack.Screen: Defines each screen in the stack.
See also  Day 9: Converting an Existing React App into a PWA

Step 3: Create the Home and Details Screens

Next, create two new files inside a screens folder:

  1. HomeScreen.js
  2. DetailsScreen.js

HomeScreen.js:

import React from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';

export default function HomeScreen({ navigation }) {
  return (
    <View style={styles.container}>
      <Text style={styles.title}>Welcome to the Home Screen</Text>
      <Button
        title="Go to Details"
        onPress={() => navigation.navigate('Details')}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f5f5f5',
  },
  title: {
    fontSize: 24,
    marginBottom: 20,
  },
});

DetailsScreen.js:

import React from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';

export default function DetailsScreen({ navigation }) {
  return (
    <View style={styles.container}>
      <Text style={styles.title}>This is the Details Screen</Text>
      <Button
        title="Go Back"
        onPress={() => navigation.goBack()}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f5f5f5',
  },
  title: {
    fontSize: 24,
    marginBottom: 20,
  },
});

Explanation:

  • HomeScreen: Displays a welcome message and a button. Clicking the button navigates to the Details screen using the navigation.navigate() method.
  • DetailsScreen: Displays a message and a button to go back to the previous screen using the navigation.goBack() method.

Step 4: Pass Data Between Screens

Let’s take it up a notch by passing data from the HomeScreen to the DetailsScreen. This will make the app more dynamic, allowing us to display different content on different screens based on the data passed.

Modify HomeScreen.js as follows to pass some data:

export default function HomeScreen({ navigation }) {
  return (
    <View style={styles.container}>
      <Text style={styles.title}>Welcome to the Home Screen</Text>
      <Button
        title="Go to Details"
        onPress={() => navigation.navigate('Details', { itemId: 42, message: 'Hello from Home!' })}
      />
    </View>
  );
}

Next, modify DetailsScreen.js to receive and display the data:

export default function DetailsScreen({ route, navigation }) {
  const { itemId, message } = route.params;

  return (
    <View style={styles.container}>
      <Text style={styles.title}>This is the Details Screen</Text>
      <Text>Item ID: {itemId}</Text>
      <Text>Message: {message}</Text>
      <Button
        title="Go Back"
        onPress={() => navigation.goBack()}
      />
    </View>
  );
}

Explanation:

  • In HomeScreen, we passed two pieces of data: itemId and message using navigation.navigate('Details', { itemId: 42, message: 'Hello from Home!' }).
  • In DetailsScreen, we received the data via the route.params object and displayed it on the screen.
See also  Day 4: Handling Side Effects with Redux-Saga

Step 5: Testing the App

Let’s test the app. After implementing the changes, run the app with npm start and scan the QR code using the Expo Go app on your mobile device. You should be able to:

  1. Navigate from the Home screen to the Details screen.
  2. See the data (itemId and message) passed from the Home screen displayed on the Details screen.
  3. Return to the Home screen by pressing the Go Back button.

Step 6: Customizing the Navigation Bar

React Navigation allows you to customize the appearance of the navigation bar. You can modify the title, header style, and colors for each screen.

Let’s customize the HomeScreen navigation bar.

  1. Open App.js.
  2. Add a options prop to the Stack.Screen for Home:
<Stack.Screen 
  name="Home" 
  component={HomeScreen} 
  options={{ 
    title: 'My Home', 
    headerStyle: { backgroundColor: '#6200EE' }, 
    headerTintColor: '#fff', 
    headerTitleStyle: { fontWeight: 'bold' } 
  }} 
/>

Explanation:

  • title: Changes the text displayed in the navigation bar.
  • headerStyle: Styles the navigation bar background.
  • headerTintColor: Changes the color of the text in the navigation bar.
  • headerTitleStyle: Adds custom styling to the navigation bar title.

After saving, the navigation bar for the Home screen will have a purple background and white text.


Step 7: Adding More Screens (Optional)

If you want to add more screens to your app, the process is the same. You can create additional screens and add them to the stack navigator like this:

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

Make sure to create a new component for AnotherScreen in the screens folder.


Step 8: Recap and Summary

Today, you learned how to implement navigation in your mobile app using React Navigation. Here’s a quick summary of what you’ve done:

  • Installed and set up React Navigation.
  • Created multiple screens (Home and Details).
  • Added navigation between screens using a stack navigator.
  • Passed data between screens.
  • Customized the navigation bar for better UX.
See also  Day 10: Integrating Analytics with Firebase in React Native

Your app now has the ability to navigate between different screens, making it feel more complete and structured. You’ve also learned how to pass data between screens, which is essential for building interactive apps.


Next Up: Day 4 – Handling User Input and Forms

In Day 4, we will focus on handling user input in forms and responding to user actions. You’ll learn how to capture text input, handle button presses, and manage state in your app.

Stay tuned for more interactive functionality tomorrow!


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.