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 init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

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

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

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-gesture-handler, react-native-reanimated, react-native-screens and react-native-safe-area-context and @react-native-community/masked-view

npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view --save

3. For the Stack Navigator install

npm install @react-navigation/stack --save

Note: When you use a navigator (such as stack navigator), you’ll need to follow the installation instructions of that navigator for any additional dependencies. If you’re getting an error “Unable to resolve module”, you need to install that module in your project.

You might get warnings related to peer dependencies after installation. They are usually caused by incorrect version ranges specified in some packages. You can safely ignore most warnings as long as your app builds.

CocoaPods Installation

Please use the following command to install CocoaPods

npx pod-install ios

To finalize the installation of react-native-gesture-handler, add the following at the top (make sure it’s at the top and there’s nothing else before it) of your entry files, such as index.js or App.js:

import 'react-native-gesture-handler';

Note: If you skip this step, your app may crash in production even if it works fine in development.

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-native-gesture-handler';

import React from 'react';

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

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

const Stack = createStackNavigator();

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

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

react-native run-android

or on the iOS Simulator by running (macOS only)

react-native run-ios

Download Source Code

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. 🙂

25 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
    • You can not directly send the data to the 3rd and 4th screen you have to take the data in the middle screen and pass the same from there also. You can also use async storage to store the value and you can access those values any time.

      Reply
  4. hello everyone can u help me i sending a value from one Screen to another screen using functional components but i din get this value another Screen soo what should i do?

    Reply
  5. Hi i followed the above code,it worked well,similarly, i implemented for fetch api call,where we make an api call and corresponding data is displayed .I am getting the data display,but it will display on next page only after i go back and again load that page.
    Can you please help me

    Reply
  6. I am trying to pass multi values from one screen to another screen.
    just to know what value is being passed in first name, Im trying to get the value over console but everytime its giving me error that variable doesn’t exist.

    Reply
  7. i have error undefined is not an object (evaluating ‘route.parrams.parramKey’) i cant fix this. i try to search about 2 week @@

    Reply

Leave a Comment

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