Home » React Native Passing Value between Screen

React Native Passing Value between Screen

by Online Tutorials Library

React Native Passing Value between Screen

While creating an app containing multiple screens, then sometimes it is required to pass value between one screen to another. This can be achieved by using this.props.navigation.navigate() function.

This function is used to navigate between the different screens.

Before diving into this example, you need to first go through React Native Navigation.

Example

In this example, we will input the value in the first screen and get it into the second screen.

The value (param) is passed as an object in the first screen to the navigation.navigate function as:

The same value (param) is read in the second screen as:

Create a HomeScreen.js file and add a TextInput component for input value and a Button to submit. The TextInput component has an onChangeText prop which takes a function which is to be called whenever the text changed.

HomeScreen.js

In the above code userName: this.state.username, store the value input into the TextInput component and otherParam: ‘101’ directly assign a value. On clicking the Button userName and otherParam is passed to Profile screen.

ProfileScreen.js

In this screen, we receive the value of userName and otherParam using navigation.getParam(‘paramValue’, default value) and stored into object user_name and other_param respectively. The value of JavaScript object is converted to string using JSON.stringify(object) function.

App.js

Create the App.js file as it is the entry point of the app and imports the HomeScreen and ProfileScreen. The HomeScreen set as the first screen using the initialRouteName.

Output:

React Native Passing Value between Screen React Native Passing Value between Screen
React Native Passing Value between Screen React Native Passing Value between Screen

We also send and receive the parameters into JSON such as:

HomeScreen.js

ProfileScreen.js

This screen read the value in two ways without checking.

Or checking the input value is null or not

Output:

React Native Passing Value between Screen React Native Passing Value between Screen
React Native Passing Value between Screen React Native Passing Value between Screen


You may also like