Skip to main content

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.

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:

  1. this.props.navigation.navigate('RouteName', { /* params go here */ })   

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

  1. this.props.navigation.getParam(paramName, defaultValue)   
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

  1. import React from 'react';  
  2. //import react in our code.  
  3. import { StyleSheet, View, Button, TextInput } from 'react-native';  
  4.   
  5. export default class HomeScreen extends React.Component {  
  6.   
  7.     constructor(props) {  
  8.         //constructor to set default state  
  9.         super(props);  
  10.         this.state = {  
  11.             username: '',  
  12.         };  
  13.     }  
  14.     static navigationOptions = {  
  15.         title: 'Home',  
  16.         headerStyle: {  
  17.             backgroundColor: '#f4511e',  
  18.         },  
  19.         //headerTintColor: '#0ff',  
  20.         headerTitleStyle: {  
  21.             fontWeight: 'bold',  
  22.         },  
  23.     };  
  24.   
  25.     render() {  
  26.         const { navigate } = this.props.navigation;  
  27.         return (  
  28.             //View to hold our multiple components  
  29.             <View style={styles.container}>  
  30.             {/*Input to get the value from the user*/}  
  31.             <TextInput  
  32.         value={this.state.username}  
  33.         onChangeText={username => this.setState({ username })}  
  34.         placeholder={'Enter Any value'}  
  35.         style={styles.textInput}  
  36.         />  
  37.         <View style={styles.buttonStyle}>  
  38.             <Button  
  39.         title="Submit"  
  40.         // color="#00B0FF"  
  41.         onPress={() =>  
  42.         this.props.navigation.navigate('Profile', {  
  43.             userName: this.state.username,  
  44.             otherParam: '101',  
  45.         })  
  46.     }  
  47.         />  
  48.         </View>  
  49.         </View>  
  50.     );  
  51.     }  
  52. }  
  53. const styles = StyleSheet.create({  
  54.     container: {  
  55.         flex: 1,  
  56.         backgroundColor: '#fff',  
  57.         alignItems: 'center',  
  58.         padding: 16,  
  59.     },  
  60.     textInput: {  
  61.         height: 45,width: "95%",borderColor: "gray",borderWidth: 1,fontSize:20,  
  62.     },  
  63.     buttonStyle:{  
  64.         width: "93%",  
  65.         marginTop: 50,  
  66.         backgroundColor: "red",  
  67.     }  
  68. });  

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.

  1. import React from 'react';  
  2. import { StyleSheet, View, Text, Button } from 'react-native';  
  3.   
  4. export default class ProfileScreen extends React.Component {  
  5.     static navigationOptions = {  
  6.         title: 'Profile',  
  7.         headerStyle: {  
  8.             backgroundColor: '#f4511e',  
  9.         },  
  10.         //headerTintColor: '#0ff',  
  11.         headerTitleStyle: {  
  12.             fontWeight: 'bold',  
  13.         },  
  14.     };  
  15.     render() {  
  16.         {/*Using the navigation prop we can get the 
  17.               value passed from the previous screen*/}  
  18.         const { navigation } = this.props;  
  19.         const user_name = navigation.getParam('userName''NO-User');  
  20.         const other_param = navigation.getParam('otherParam''some default value');  
  21.         return (  
  22.             <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>  
  23.                 <Text style={{ marginTop: 16,fontSize: 20,}}>  
  24.                     This is Profile Screen and we receive value from Home Screen  
  25.                 </Text>  
  26.                 <Text style={styles.textStyle}>User Name: {JSON.stringify(user_name)}</Text>  
  27.                 <Text style={styles.textStyle}>Other Param: {JSON.stringify(other_param)}</Text>  
  28.                 <View style={styles.buttonStyle}>  
  29.                 <Button  
  30.                     title="Go back"  
  31.                     onPress={() => this.props.navigation.goBack()}  
  32.                 />  
  33.                 </View>  
  34.             </View>  
  35.         );  
  36.     }  
  37. }  
  38. const styles = StyleSheet.create({  
  39.     textStyle: {  
  40.         fontSize: 23,  
  41.         textAlign: 'center',  
  42.         color: '#f00',  
  43.     },  
  44.   
  45.     buttonStyle:{  
  46.         width: "93%",  
  47.         marginTop: 50,  
  48.         backgroundColor: "red",  
  49.     }  
  50. });  

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.

  1. import React from 'react';  
  2. import {createStackNavigator,createAppContainer} from 'react-navigation';  
  3. import HomeScreen from './HomeScreen';  
  4. import ProfileScreen from './ProfileScreen';  
  5.   
  6. const AppNavigator = createStackNavigator(  
  7.     {  
  8.         Home: HomeScreen,  
  9.         Profile: ProfileScreen  
  10.     },  
  11.     {  
  12.         initialRouteName: "Home"  
  13.     }  
  14. );  
  15. export default createAppContainer(AppNavigator);  

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

  1. onPress={() =>  
  2.     navigate('Profile', {  
  3.         JSON_ListView_Clicked_Item: this.state.username,  
  4.     })  
  5. }  

ProfileScreen.js

This screen read the value in two ways without checking.

  1. {this.props.navigation.state.params.JSON_ListView_Clicked_Item}  
Or checking the input value is null or not

  1. {this.props.navigation.state.params.JSON_ListView_Clicked_Item  
  2.    ? this.props.navigation.state.params.JSON_ListView_Clicked_Item  
  3.     : 'No Value Passed'}  

  1. <Text style={styles.textStyle}>  
  2.         {this.props.navigation.state.params.JSON_ListView_Clicked_Item}  
  3.     </Text>  
  4. <Text style={{ marginTop: 16,fontSize: 20, }}>With Check</Text>  
  5.     {/*If you want to check the value is passed or not, 
  6.             you can use conditional operator.*/}  
  7. <Text style={styles.textStyle}>  
  8.     {this.props.navigation.state.params.JSON_ListView_Clicked_Item  
  9.         ? this.props.navigation.state.params.JSON_ListView_Clicked_Item  
  10.         : 'No Value Passed'}  

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

Comments

Popular Posts

Reloading UITableView while Animating Scroll in iOS 11

Reloading UITableView while Animating Scroll Calling  reloadData  on  UITableView  may not be the most efficient way to update your cells, but sometimes it’s easier to ensure the data you are storing is in sync with what your  UITableView  is showing. In iOS 10  reloadData  could be called at any time and it would not affect the scrolling UI of  UITableView . However, in iOS 11 calling  reloadData  while your  UITableView  is animating scrolling causes the  UITableView  to stop its scroll animation and not complete. We noticed this is only true for scroll animations triggered via one of the  UITableView  methods (such as  scrollToRow(at:at:animated:) ) and not for scroll animations caused by user interaction. This can be an issue when server responses trigger a  reloadData  call since they can happen at any moment, possibly when scroll animation is occurring. Example of s...

What are the Alternatives of device UDID in iOS? - iOS7 / iOS 6 / iOS 5 – Get Device Unique Identifier UDID

Get Device Unique Identifier UDID Following code will help you to get the unique-device-identifier known as UDID. No matter what iOS user is using, you can get the UDID of the current iOS device by following code. - ( NSString *)UDID { NSString *uuidString = nil ; // get os version NSUInteger currentOSVersion = [[[[[UIDevice currentDevice ] systemVersion ] componentsSeparatedByString: @" . " ] objectAtIndex: 0 ] integerValue ]; if (currentOSVersion <= 5 ) { if ([[ NSUserDefaults standardUserDefaults ] valueForKey: @" udid " ]) { uuidString = [[ NSUserDefaults standardDefaults ] valueForKey: @" udid " ]; } else { CFUUIDRef uuidRef = CFUUIDCreate ( kCFAllocatorDefault ); uuidString = ( NSString *) CFBridgingRelease ( CFUUIDCreateString ( NULL ,uuidRef)); CFRelease (uuidRef); [[ NSUserDefaults standardUserDefaults ] setObject: uuidString ForKey: @" udid " ]; [[ NSUserDefaults standardUserDefaults ] synchro...

Xcode & Instruments: Measuring Launch time, CPU Usage, Memory Leaks, Energy Impact and Frame Rate

When you’re developing applications for modern mobile devices, it’s vital that you consider the performance footprint that it has on older devices and in less than ideal network conditions. Fortunately Apple provides several powerful tools that enable Engineers to measure, investigate and understand the different performance characteristics of an application running on an iOS device. Recently I spent some time with these tools working to better understand the performance characteristics of an eCommerce application and finding ways that we can optimise the experience for our users. We realised that applications that are increasingly performance intensive, consume excessive amounts of memory, drain battery life and feel uncomfortably slow are less likely to retain users. With the release of iOS 12.0 it’s easier than ever for users to find applications that are consuming the most of their device’s finite amount of resources. Users can now make informed decisions abou...