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. Using :
    this.props.navigation.navigate('RouteName', { /* params go here */ })
  2. Read the params in your Second screen. Using:
    this.props.navigation.getParam(paramName, defaultValue)

This example is updated for the React Navigation 4.0+. For more about React Navigation 4 please have a look at Using React Navigation 4.0 in React Native apps.

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 switch between the screens we need to add react-navigation in our application.

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

cd ProjectName

1. Install react-navigation dependency to import createAppContainer

npm install react-navigation --save

2. Other supporting libraries for react-navigation

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

3. Install react-navigation-stack to import createStackNavigator

npm install react-navigation-stack --save

These commands will copy all the dependencies into your node_module directory.

CocoaPods Installation

Please use the following command to install CocoaPods

cd ios && pod install && cd ..

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

//This is an example code to pass values between two screens using React Navigator// 
import React, { Component } from 'react';

//Import react-navigation
import { createAppContainer } from 'react-navigation';
import { createStackNavigator} from 'react-navigation-stack';

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

//import all the screens we are going to switch 
const App = createStackNavigator({
  //Constant which holds all the screens like index of any book 
    FirstPage: { screen: FirstPage }, 
    //First entry by default be our first screen 
    //if we do not define initialRouteName
    SecondPage: { screen: SecondPage }, 
  },
  {
    initialRouteName: 'FirstPage',
  }
);
export default createAppContainer(App);

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

FirstPage.js

// First screen which we will use to send the data
import React, { Component } from 'react';
//import react in our code.
import { StyleSheet, View, Button, TextInput } from 'react-native';
//import all the components we are going to use.

export default class FirstPage extends Component {
  constructor(props) {
    //constructor to set default state
    super(props);
    this.state = {
      username: '',
    };
  }
  static navigationOptions = {
    //Setting the header of the screen
    title: 'First Page',
  };

  render() {
    const { navigate } = this.props.navigation;
    return (
      //View to hold our multiple components
      <View style={styles.container}>
        {/*Input to get the value from the user*/}
        <TextInput
          value={this.state.username}
          onChangeText={username => this.setState({ username })}
          placeholder={'Enter Any value'}
          style={styles.input}
        />
        {/*Button to go to the next activity*/}
        <Button
          title="Go Next"
          //Button Title
          onPress={() =>
            navigate('SecondPage', {
              JSON_ListView_Clicked_Item: this.state.username,
            })
          }
          //On click of the button we will send
          //the data as a Json from here to the Second Screen using navigation prop
        />
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    padding: 16,
  },
  input: {
    width: 200,
    height: 44,
    padding: 10,
    marginBottom: 10,
    backgroundColor: '#DBDBD6',
  },
});

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

SecondPage.js

// Second screen which we will use to get the data
import React, { Component } from 'react';
//import react in our code.
import { StyleSheet, View, Text } from 'react-native';
//import all the components we are going to use.

export default class SecondPage extends Component {
  static navigationOptions = {
    //Setting the header of the screen
    title: 'Second Page',
  };
  render() {
    const { navigate } = this.props.navigation;
    return (
      //View to hold our multiple components
      <View style={styles.container}>
        <Text>
          You are on SecondPage and the value passed from the first screen is
        </Text>
        {/*Using the navigation prop we can get the value passed from the first Screen*/}
        <Text style={styles.TextStyle}>
          {this.props.navigation.state.params.JSON_ListView_Clicked_Item}
        </Text>
        <Text style={{ marginTop: 16 }}>With Check</Text>
        {/*If you want to check the value is passed or not, 
         you can use conditional operator.*/}
        <Text style={styles.TextStyle}>
          {this.props.navigation.state.params.JSON_ListView_Clicked_Item
            ? this.props.navigation.state.params.JSON_ListView_Clicked_Item
            : 'No Value Passed'}
        </Text>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    margin: 50,
    alignItems: 'center',
    justifyContent: 'center',
  },
  TextStyle: {
    fontSize: 23,
    textAlign: 'center',
    color: '#f00',
  },
});

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
react-native run-ios (macOS only).

Output Screenshots

     

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


Related Posts

23 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
  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. i wanna take value from 1 to 3 page.
    i am passing 1 to 2 and 2 to 3 its not working, how to do that using react native navigation

    Reply
  5. Hi, when I am trying this approach, I get always default value not that one which I am sending from the first screen.
    1)First screen
    this.props.navigation.navigate(‘AnotherScreen’, { text: ‘some text’ })
    2)AnotherScreen
    this.props.navigation.getParam(‘text’, ‘defaultValue’)

    And when I am fallowed your way I got “undefined” from this.props.navigation.state.params.text

    My version of react navigation is : 4.0.1 .

    Reply

Leave a Comment

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