React Native Navigation: Tutorial with Examples

This React Native Navigation tutorial was last updated on December 1, 2022 and contains information about the latest version of React Navigation (v6 at the time of writing), as well as a section comparing React Navigation with the React Router library. Check out React Navigation vs React Native Navigation: Which is right for you? to know more information.

Mobile apps consist of multiple screens. When building a mobile app, a major concern is how to handle user navigation within the app, such as the presentation of screens and transitions between screens.

React Navigation is one of the most well-known navigation libraries for React. In this tutorial, we'll cover the basics of React Native navigation, show you how to start using React Navigation in a React Native application, and walk through some React Native navigation examples.

What is react navigation?

React Navigation is a standalone library and 8 Ways to Fix Windows 11 Black Screen Issue enables you to implement navigation functionality in React Native applications.

React Navigation is written in JavaScript and does not directly use the native navigation API on iOS and Android. Instead, it recreates some subset of these APIs. This allows third-party JS plug-ins to be integrated for maximum customization and easier debugging without having to learn Objective-C, Swift, Java, Kotlin, etc.

React Navigation 6.0

As of this writing, the most stable version of React Navigation is React Navigation 6.0, released in August 2021. According to their release post, the latest version focuses on flexibility and ease of use. However, the team also said that this latest version brings few major changes.

Some of the new features included in React Navigation 6.0 include:

  • Flexible customization options for the Navigator: This means developers can now further tweak the look and feel of the Navigator

  • Group component: The Group element allows users to share screen options and configurations between screens in a project. Therefore this allows for more organization and code readability

  • Component library: Starting from v6, the Navigation team created an elements component library. This is useful for situations where the user wants to build a custom navigator

  • Native navigation: The library now uses native-stack under the hood by default. This means that on older devices, navigation between large screens is faster and less demanding

  • Flipper plugin: This tool allows developers to debug their applications and track performance. How to delete/disable recently used files from File Explorer In the latest version, there is now an official React Navigation plugin that makes the testing process easier

What is React Native navigation?

React Native Navigation is a popular alternative to React Navigation. It is a module that depends on and is designed to be used with React Native. React Native Navigation is slightly different in that it directly uses the native navigation API on iOS and Android, thus providing a more native look and feel.

To explore the differences between React Navigation and React Native Navigation in more detail, check out “ React Navigation vs. React Native Navigation: Which Is Right for You? ”

Another option: React Router Native

React Router Native is another solution for implementing navigation functionality in React Native applications. It is developed by the Remix team, which is famous for its modern web framework.

Shares most of its API code React Router Native with the React Router framework. This means that web developers who have used React Router will find it easy to start using its Native version.

In terms of ease of use, React Navigation and React Router Native are identical. For example, look at the following Router Native code:

import { NativeRouter, Route, Link } from "react-router-native";
const Home = () => <Text>Home</Text>;
const About = () => <Text>About</Text>;
const App = () => (
  <NativeRouter>
    <View>
      <View>
        {/* Define our links. They are like anchor tags */}
        <Link to="/">
          <Text>Home</Text>
        </Link>
        <Link to="/about">
          <Text>About</Text>
        </Link>
      </View>
      {/*Define our routes for this project*/}
      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
    </View>
    {/*The NativeRouter*/}
  </NativeRouter>
);

Compared to Navigation, we can see that the code is similar:

import { NavigationContainer } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
function HomeScreen() {
  return (
    <View>
      <Text>Home Screen</Text>
    </View>
  );
}
function AboutScreen() {
  return (
    <View>
      <Text>About Screen</Text>
    </View>
  );
}
const Stack = createNativeStackNavigator();
export default function App() {
  return (
    <NavigationContainer>
     <Stack.Navigator>
        {/*Define our routes*/}
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="About" component={AboutScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

The code used to implement routing in both libraries is identical to each other. This is a major advantage as it means there is a smaller learning curve for both frameworks.

If you have a web development background, I would recommend React Router Native as its usage is the same as React Router. Otherwise, React Navigation should be the right choice, Interesting Notes - Share valuable tutorials! Because it has a larger community, it can provide more development support.

Install React Navigation

Assuming you have Yarn installed, the first step is to set up your React Native application. The easiest way to get started with React Native is to use the Expo tools, as they allow you to start a project without installing and configuring Xcode or Android Studio.

First, initialize a blank Expo application using the following bash command:

npx create-expo-app ReactNavigationDemo

This will start the download process and configure the project:

Next, cd into the project folder and open the code editor:

cd ReactNavigationDemo

If you are using VS Code, you can use the following command to open the current folder in the editor:

code .

Start the application using the following command:

npx expo start

The next step is to install the library React Native from the react-navigation project:

npm install @react-navigation/native
npx expo install react-native-screens react-native-safe-area-context

React Native Stack Navigator

React Navigation is built using JavaScript, allowing you to create components and navigation patterns that look and feel like true native.

React Navigation uses so-called stack navigators to manage navigation history and the rendering of corresponding screens based on the route the user takes within the application. Only one screen is presented to the user at a given time.

Imagine a stack of paper; navigating to a new screen puts it on top of the stack, and navigating backwards removes it from the stack. Stack Navigator also provides native iOS and Android-like transitions and gestures. Note that an application can have multiple stack navigators.

React Native navigation example

In this section, we will explore some examples of React Native navigation patterns and how to implement them using the React Navigation library.

1. Navigate between screen components using the stack navigator

Let's first create a /components folder located in the root of our project. Then we create two files, Homescreen.js and Aboutscreen:

// Homescreen.js
import React from "react";
import { Button, View, Text } from "react-native";
​
export default function HomeScreen({ navigation }) {
  return (
    <View style={
  
  { flex: 1, alignItems: "center", justifyContent: "center" }}>
      <Text>Home Screen</Text>
      <Button
        title="Go to About"
        onPress={() => navigation.navigate("About")}
      />
    </View>
  );
}

Note the prop for the button above onPress - we'll explain what it does later.

// Aboutscreen.js
import React, { Component } from "react";
import { Button, View, Text } from "react-native";
export default function AboutScreen() {
  return (
    <View style={
  
  { flex: 1, alignItems: "center", justifyContent: "center" }}>
      <Text>About Screen</Text>
    </View>
  );
}

Your project folder should look like this:

Let's also make some changes to App.js. Here we have to make the following imports:

//tell React that we will implement a navigator
import { NavigationContainer } from "@react-navigation/native";
//create a stack navigator
import { createNativeStackNavigator } from "@react-navigation/native-stack";

It's useful to implement our navigation in the root App.js file because components exported from App.js are the entry point (or root component) of a React Native application and all other components are descendants.

As you will see, we will wrap all other components in the navigation function:

// App.js
import * as React from "react";
import { View, Text } from "react-native";
import { NavigationContainer } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import HomeScreen from "./components/HomeScreen";
import AboutScreen from "./components/AboutScreen";

const Stack = createNativeStackNavigator();

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

In the code above, createNativeStackNavigator provides a way for our application to transition between screens, where each new screen is placed on top of the stack. It's configured to have a familiar iOS and Android look and feel: The new screen slides in from the right on iOS and fades in from the bottom on Android.

Here, we have executed the createNativeStackNavigator function and stored its instance into the Stack mutable.

Later, we will pass our route the Stack.Screen tag using the following. The Home route corresponds to HomeScreen, and the About route corresponds to AboutScreen.

The createStackNavigator function is passed behind the scenes to navigate to the HomeScreen and AboutScreen components. This property allows navigation to the specified screen component. This is why we are able to use HomeScreen.js on a button that, when pressed, results in an AboutScreen page, as shown below:

<Button title="Go to About" onPress={() => navigation.navigate("About")} />;

In the App.js code, we finally create an application container by wrapping the component in a NavigationContainer tag. This container manages navigation state.

To run this application, you need to download the Expo client application. You can get iOS and Android versions. Make sure your command line points to the project folder and run the following command:

npx expo start

You should see a QR code displayed on your terminal. Use the Expo app on Android to scan the QR code, and for the iOS app you can scan using the regular iPhone camera, which will prompt you to click the command to open the Expo app:

2. Use tab navigation

Most mobile apps have multiple screens. A common navigation style in such mobile applications is tab-based navigation. Here we focus on how to use the createBottomTabNavigator function.

Before implementing tab-based navigation, we must first install the bottom-tabs module like this:

npm install @react-navigation/bottom-tabs

Let’s add another screen to our application by creating a ContactScreen.js file under /components:

import React, { Component } from "react";
import { Button, View, Text } from "react-native";

export default function ContactScreen() {
  return (
    <View style={
  
  { flex: 1, alignItems: "center", justifyContent: "center" }}>
      <Text>Contact Screen</Text>
    </View>
  );
}

Now let's add the import to the top of the App.js file:

import ContactScreen from './components/ContactScreen';

Recall that it is useful to implement navigation in the root App.js component. Therefore, we will implement our tab navigation by importing createBottomTabNavigator in App.js. Let's replace createStackNavigator with this line of code:

import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';

Additionally, run the createBottomTabNavigator function:

const Tab = createBottomTabNavigator();

//further code...
<NavigationContainer>
  <Tab.Navigator initialRouteName="Home">
    <Tab.Screen name="Home" component={HomeScreen} />
    <Tab.Screen name="About" component={AboutScreen} />
  </Tab.Navigator>
</NavigationContainer>;

Add a new screen Tab.Screen part using the following command:

<Tab.Navigator>
  <Tab.Screen name="Home" component={HomeScreen} />
  <Tab.Screen name="About" component={AboutScreen} />
  <Tab.Screen name="Contact" component={ContactScreen} />
</Tab.Navigator>

If you run the application npm start and open it on your Expo client, you should see the bottom navigation implemented:

3. Use drawer navigation

To start implementing the navigation drawer immediately, first install the required dependencies:

npm install @react-navigation/drawer
npx expo install react-native-gesture-handler react-native-reanimated

Next, go to the Reanimated documentation to set up gesture controls in your project.

After completing this step, write these import statements into App.js:

import "react-native-gesture-handler"; //this should be the first import in your code
import { createDrawerNavigator } from "@react-navigation/drawer";

Let’s also update the AppNavigator’s changeability:

const Drawer = createDrawerNavigator();
<Drawer.Navigator initialRouteName="Home">
  <Stack.Screen name="Home" component={HomeScreen} />
  <Stack.Screen name="About" component={AboutScreen} />
  <Stack.Screen name="Contact" component={ContactScreen} />
</Drawer.Navigator>

If you npm start you should be able to see the changes immediately. Swipe from the left to view the navigation drawer:

You can customize the navigation drawer by adding an icon next to the route name. In the assets folder of the project, there are currently three icons:

We can customize navigationOptions by adding to the following screen component file:

<NavigationContainer>
  <Drawer.Navigator initialRouteName="Home">
    <Drawer.Screen
      name="Home"
      component={HomeScreen}
      options={
  
  { //change the configuration of our screen
        drawerIcon: ({ color, number, focused }) => { //set the icon:
          return ( //the icon will be an image
            <Image
              source={require("../assets/home-icon.png")}
              style={
  
  { height: 30, width: 30 }}
            />
          );
        },
      }}
    />
    <Drawer.Screen
      name="About"
      component={AboutScreen}
      options={
  
  {
        drawerIcon: ({ color, number, focused }) => { //set the icon for all screens
          return (
            <Image
              source={require("../assets/about-icon.png")}
              style={
  
  { height: 30, width: 30 }}
            />
          );
        },
      }}
    />
    <Drawer.Screen
      name="Contact"
      component={ContactScreen}
      options={
  
  {
        drawerIcon: ({ color, number, focused }) => {
          return (
            <Image
              source={require("../assets/contact-icon.png")}
              style={
  
  { height: 30, width: 30 }}
            />
          );
        },
      }}
    />
  </Drawer.Navigator>
</NavigationContainer>

The drawerActiveTintColorprop allows you to apply any color based on the active or inactive state of navigation tabs and labels. For example, we can change the active state color of the navigation drawer label. Go to the Drawer.Navigator variable and add to the options object:

<Drawer.Navigator
  initialRouteName="Home"
  screenOptions={
  
  { drawerActiveTintColor: "#e91e63" }}
>
//... further code.

This results in a color change:

Pass parameters to screen in React Navigation

There are two simple steps to passing parameters to a route:

  1. Pass parameters to a route by putting them into an object as the second parameter

    navigation.navigate

    Function:

    navigation.navigate('RouteName', { /* params go here */ })
  2. Read parameters in the screen component:

    export default function HomeScreen({ route, navigation }) {
    ​
    //the 'route' variable gives us information on the page.
    ​
    //It also stores the parameters and their values
    ​
    const { paramName } = route; //our parameter 'paramName' is stored here.
    ​
    //..further code..
    ​
    }

Finally, to set the title title, we can use the title property of the options prop like this:

<Drawer.Screen
  name="Home"
  component={HomeScreen}
  options={
  
  {
    title: "Home Page", //set the title of the page to 'Home page'
  }}
/>

in conclusion

I hope this article helps you quickly use the React Navigation package in your existing or future React Native projects.

There's a lot more to do, and React Navigation will meet most of your needs. To learn more, check out the React Navigation documentation, and feel free to grab the final code from my GitHub repository.

Guess you like

Origin blog.csdn.net/weixin_47967031/article/details/132910876