React Native Pass Value From One Screen to Another Using React Navigation

Introduction

Passing the value from one screen to another is one of the most useful things while we have an application that needs to communicate between the different screens. We can easily pass the data between different activities easily using this.props.navigation.navigate() which is used to navigate between different screens. In the same method, we can easily pass the value and can get it from other screens.

In our example below, we will pass an input taken from the first screen to the second screen.

To pass the value between different activities

  1. Pass params to a route by putting them in an object as a second parameter to the navigation.navigate function from First Screen
    navigation.navigate('SecondPage', {
      paramKey: 'Some Param from previous Screen',
    })
  2. Read the params in your Second screen. Using:
    route.params.paramKey

Let’s see how to pass value from one screen to another using React Navigation.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react native command line interface to make our React Native App.

If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:

npm uninstall -g react-native-cli @react-native-community/cli

Run the following commands to create a new React Native project

npx react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

npx react-native init ProjectName --version X.XX.X

Note If the above command is failing, you may have old version of react-native or react-native-cli installed globally on your pc. Try uninstalling the cli and run the cli using npx.

This will make a project structure with an index file named App.js in your project directory.

Installation of Dependencies

To navigate between screens we need to add react-navigation and other supporting dependencies.

To install the dependencies open the terminal and jump into your project

cd ProjectName

1. Install react-navigation

npm install @react-navigation/native --save

2. Other supporting libraries react-native-screens and react-native-safe-area-context

npm install react-native-screens react-native-safe-area-context --save

react-native-screens package requires one additional configuration step to properly work on Android devices. Edit MainActivity.java file which is located in android/app/src/main/java/<your package name>/MainActivity.java.

Add the following code to the body of MainActivity class:

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(null);
}

and make sure to add the following import statement at the top of this file below your package statement:

import android.os.Bundle;

This change is required to avoid crashes related to View state being not persisted consistently across Activity restarts.

3. For the Stack Navigator install

npm install @react-navigation/native-stack --save

CocoaPods Installation

Please use the following command to install CocoaPods

npx pod-install

Project File Structure

To start with this Example you need to create a directory named pages in your project and create two files FirstPge.js and SecondPage.js in it.

Code

Now open App.js in any code editor and replace the code with the following code

App.js

// React Native Pass Value From One Screen to Another Using React Navigation
// https://aboutreact.com/react-native-pass-value-from-one-screen-to-another-using-react-navigation/


import React from 'react';

import {NavigationContainer} from '@react-navigation/native';
import {createNativeStackNavigator} from '@react-navigation/native-stack';

import FirstPage from './pages/FirstPage';
import SecondPage from './pages/SecondPage';

const Stack = createNativeStackNavigator();

const App = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="FirstPage">
        <Stack.Screen
          name="FirstPage"
          component={FirstPage}
          options={{
            title: 'First Page', //Set Header Title
            headerStyle: {
              backgroundColor: '#f4511e', //Set Header color
            },
            headerTintColor: '#fff', //Set Header text color
            headerTitleStyle: {
              fontWeight: 'bold', //Set Header text style
            },
          }}
        />
        <Stack.Screen
          name="SecondPage"
          component={SecondPage}
          options={{
            title: 'Second Page', //Set Header Title
            headerStyle: {
              backgroundColor: '#f4511e', //Set Header color
            },
            headerTintColor: '#fff', //Set Header text color
            headerTitleStyle: {
              fontWeight: 'bold', //Set Header text style
            },
          }}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
};

export default App;

Open pages/FirstPage.js in any code editor and replace the code with the following code

FirstPage.js

// React Native Pass Value From One Screen to Another Using React Navigation
// https://aboutreact.com/react-native-pass-value-from-one-screen-to-another-using-react-navigation/

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

const FirstPage = ({navigation}) => {
  const [userName, setUserName] = useState('AboutReact');

  return (
    <SafeAreaView style={{flex: 1}}>
      <View style={styles.container}>
        <Text style={styles.heading}>
          React Native Pass Value From One Screen to Another
          Using React Navigation
        </Text>
        <Text style={styles.textStyle}>
          Please insert your name to pass it to second screen
        </Text>
        {/*Input to get the value from the user*/}
        <TextInput
          value={userName}
          onChangeText={(username) => setUserName(username)}
          placeholder={'Enter Any value'}
          style={styles.inputStyle}
        />
        {/* On click of the button we will send the data as a Json
          From here to the Second Screen using navigation */}
        <Button
          title="Go Next"
          //Button Title
          onPress={() =>
            navigation.navigate('SecondPage', {
              paramKey: userName,
            })
          }
        />
      </View>
      <Text style={{textAlign: 'center', color: 'grey'}}>
        www.aboutreact.com
      </Text>
    </SafeAreaView>
  );
};

export default FirstPage;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    padding: 20,
  },
  heading: {
    fontSize: 25,
    textAlign: 'center',
    marginVertical: 10,
  },
  textStyle: {
    textAlign: 'center',
    fontSize: 16,
    marginVertical: 10,
  },
  inputStyle: {
    width: '80%',
    height: 44,
    padding: 10,
    marginVertical: 10,
    backgroundColor: '#DBDBD6',
  },
});

Open pages/SecondPage.js in any code editor and replace the code with the following code

SecondPage.js

// React Native Pass Value From One Screen to Another Using React Navigation
// https://aboutreact.com/react-native-pass-value-from-one-screen-to-another-using-react-navigation/

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

const SecondPage = ({route}) => {
  return (
    <SafeAreaView style={{flex: 1}}>
      <View style={styles.container}>
        <Text style={styles.heading}>
          React Native Pass Value From One Screen to Another
          Using React Navigation
        </Text>
        <Text style={styles.textStyle}>
          Values passed from First page: {route.params.paramKey}
        </Text>
      </View>
      <Text style={{textAlign: 'center', color: 'grey'}}>
        www.aboutreact.com
      </Text>
    </SafeAreaView>
  );
};

export default SecondPage;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    padding: 20,
  },
  heading: {
    fontSize: 25,
    textAlign: 'center',
    marginVertical: 10,
  },
  textStyle: {
    textAlign: 'center',
    fontSize: 16,
    marginVertical: 10,
  },
});

To Run the React Native App

Open the terminal again and jump into your project using.

cd ProjectName

1. Start Metro Bundler

First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command

npx react-native start

Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.

2. Start React Native Application

To run the project on an Android Virtual Device or on real debugging device

npx react-native run-android

or on the iOS Simulator by running (macOS only)

npx react-native run-ios

Output Screenshots

ReactNativePassValueFromOneScreenToAnotherUsingReactNavigation1   ReactNativePassValueFromOneScreenToAnotherUsingReactNavigation2

Output in Online Emulator

This is how you can pass the value from one screen to another screen. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂

10 thoughts on “React Native Pass Value From One Screen to Another Using React Navigation”

  1. it was very useful. Now i want to know how to implement conditional operator in this. Once we entered value the value will be displayed in the next page.. now i want to know that if we didn’t enter the value an empty screen display in the second page so for that i want to show an invalid value instead of it.. can you help me out of this…

    Reply
  2. this is fine if i want to pass the value from first screen to 3rd screen what should i do?th same method is not working

    Reply
    • You have to take the value from 2nd to 3rd again..
      For example you have took the value from 1st to 2nd and then take it in a variable and while navigating to 3rd you have to take the value again..

      Instead you can also see asyncstorage..

      Reply
  3. It works perfectly. Now i want to add a button in the second page that goes back to the first page. already there is a back arrow in the second page but i need a button in second page that return to first page

    Reply
  4. I noticed sometimes you strongly recommended few changes in MainActivity.java by adding:
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(null);
    }

    Please guide whats it main purpose. Even we already have same code in MainActivity.java. The only difference is that we does not pass null here.
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    }

    please also guide what the purpose of these both, and if we ever need to change then we add another onCreate method or just replace null in existing (savedInstanceState).
    Please must guide. Thanks

    Reply
  5. You need to do it with by passing props. Means you are in parent component and you need to pass data in your all child components.

    Example:
    // Your Parent component
    function ParentComponent() {
    return ;
    }

    // Child component
    function ChildComponent(props) {
    return {props.message};
    }

    Reply

Leave a Comment

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