Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Types of Params
2.1.
Params should have
3.
Example on Passing Data Between Screens
4.
Frequently Asked Questions
4.1.
What is the use of TextInput tag in react native?
4.2.
What are params in react native?
4.3.
What kind of item should we not put in the params?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Passing Values Between Screens in React Native

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

This article will learn how to pass values between the screens while moving from one screen to another. Before learning how to pass data between screens, first learn how to move from one screen to another by referring to these articles Navigation in React Native and Moving Between Screens. We can easily pass data between screens using this.props.navigation.navigate() method, the data which wants to pass between screens is passed as a parameter also called params, in this method.

Syntax:

this.props.navigation.navigate(‘DestinationScreen’, 
{
  Id: 1212
  Name: “Ninja”
});

Explanation: Here, id and name are being passed as a parameter to the destination screen.

Click on the following link to read further: Hooks in React JS

Types of Params

It's critical to comprehend the kind of data stored in params. Params are similar to screen options. They should only contain information that allows you to customize what appears on the screen. Passing the entire data set displayed on the screen is not recommended (e.g., pass a user-id instead of a user object). Passing data that is utilized by several screens should also be avoided; such data should be stored in a global store.

Params should have

  1. It can contain id’s.
  2. You can also tell the order of element, e.g. navigation.navigate(‘News’, { sortBy: 'latest' }).
  3. We can pass timestamp, page number, or cursor for pagination.
  4. We can pass data to fill inputs on a screen to compose something.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Example on Passing Data Between Screens

Now we will make a simple app illustrating all the concepts we studied above. This section will create an app that has two screens home screen and a user screen. An input text box on the home screen will ask for the user id. The user ID we have provided on that input text box is printed on the other screen (user screen) after pressing the submit button.

Home.js

Code:

import React from 'react';  
//import react in our code.  
import { StyleSheet, View, Button, TextInput,Text } from 'react-native';  
  
export default class HomeScreen extends React.Component {  
  
    constructor(props) {  
        //constructor to set default state  
        super(props);  
        this.state = {  
            id: '',  
        };  
    }  
    static navigationOptions = {  
        title: 'Home',  
        headerStyle: {  
            backgroundColor: '#005252',  
        },  
        headerTintColor: '#ffffff',  
        headerTitleStyle: {  
            fontWeight: 'bold',  
        },  
    }; 
  
    render() {  
        const { navigate } = this.props.navigation;  
        return ( 
          <View style={styles.container}> 
                <View
                  style={{
                    flex: 1,
                    justifyContent: "center",
                    alignItems: "center",
                  }}>
                  <Text style={styles.titleText}>Home Screen</Text>
                </View>
                <TextInput  
                  value={this.state.id}  
                  onChangeText={id => this.setState({ id })}  
                  placeholder={'Enter ID'} 
                  placeholderTextColor= "white" 
                  style={styles.textInput}
               />  
                <View style={styles.buttonContainer}>  
                  <Button  
                    title="Submit"  
                    color="orange"  
                    onPress={() =>  
                    this.props.navigation.navigate('Profile', {  
                        id: this.state.id,  
                    })  
                    }  
                />  
              </View>
                <View style={styles.bottomText}>
                  <Text>
                  <Text style={styles.bottomText1}>code</Text>
                  <Text style={styles.bottomText2}>studio</Text>
                  </Text>
                  <Text>Powered By</Text>
                  <Text style={styles.bottomText3}>Coding Ninjas</Text>
                </View>  
            </View> 
    );  
    }  
}  
const styles = StyleSheet.create({  
    container: {  
        flex: 1,  
        justifyContent: 'center',
        backgroundColor: 'teal'
    },  
    buttonContainer: {
        flex: 1,  
        margin: 30,
    },
    titleText: {
      fontSize: 30,
      color: 'black',
      fontWeight: "bold",
  },
  textInput:{
      margin: 30,
      borderColor: 'white',
      borderWidth: 1,
      fontSize:20,

  },
  bottomText: {
      marginBottom:30,
      textAlign: 'center',
      alignItems: "center",
    },
    bottomText1: {
      fontSize: 25,
      fontWeight: 'bold',    
    },
    bottomText2: {
      fontSize: 25,
    },
    bottomText3: {
      fontWeight: 'bold',
      color: 'orange'
    }   
})  


user.js

Code: 

import React from 'react';  
import { StyleSheet, View, Text, Button } from 'react-native';  
  
export default class UserScreen extends React.Component {  
    static navigationOptions = {  
        title: 'User',  
        headerStyle: {  
            backgroundColor: '#005252',  
        },  
        headerTintColor: '#ffffff',  
        headerTitleStyle: {  
            fontWeight: 'bold',  
        }, 
        
    };  
    render() {  
        {/*Using the navigation prop we can get the 
              value passed from the previous screen*/}  
        const { navigation } = this.props;  
        const user_name = navigation.getParam('id');  
        return (  
            <View style={styles.container}>  
                
                <Text style={styles.titleText}>ID: {user_name}</Text>  
                
                <View style={styles.buttonContainer}>  
                <Button  
                    title="Go back"  
                    onPress={() => this.props.navigation.goBack()}  
                    color= 'orange'
                />  
                </View>
                <View style={styles.bottomText}>
                  <Text>
                  <Text style={styles.bottomText1}>code</Text>
                  <Text style={styles.bottomText2}>studio</Text>
                  </Text>
                  <Text>Powered By</Text>
                  <Text style={styles.bottomText3}>Coding Ninjas</Text>
                </View>  
            </View>  
        );  
    }  
}  
const styles = StyleSheet.create({  
    container: {  
        flex: 1,  
        justifyContent: 'center',
        backgroundColor: 'teal'
    },  
    titleText: {
      flex: 1,
      fontSize: 30,
      color: 'black',
      fontWeight: "bold",
      textAlign: 'center'
  },
  bottomText: {
      marginBottom:30,
      textAlign: 'center',
      alignItems: "center",
    },
    buttonContainer: {
        flex: 1,  
        margin: 30,
    },
    bottomText1: {
      fontSize: 25,
      fontWeight: 'bold',    
    },
    bottomText2: {
      fontSize: 25,
    },
    bottomText3: {
      fontWeight: 'bold',
      color: 'orange'
    },   
})  


App.js

Code:

import React from 'react';  
import {createAppContainer} from 'react-navigation';
import { createStackNavigator} from 'react-navigation-stack';  
import HomeScreen from './components/home';  
import UserScreen from './components/user';  
  
const AppNavigator = createStackNavigator(  
    {  
        Home: HomeScreen,  
        Profile: UserScreen  
    },  
    {  
        initialRouteName: "Home"  
    }  
);  
export default createAppContainer(AppNavigator);  


Output:

Frequently Asked Questions

What is the use of TextInput tag in react native?

The TextInput Core Component allows the user to enter text. It has a onChangeText prop that is called whenever the text is modified and a onSubmitEditing prop that is called whenever the content is submitted.

 

What are params in react native?

While transitioning from one screen to another, we sometimes want to pass or send some data to the destination screen. Params are the argument of the navigate() method of navigation package, which contains the data to be passed.

 

What kind of item should we not put in the params?

We should avoid passing the whole data to the params. We only pass small data to the other screen, such as id, type, sort, or filter. For example, we should pass user-id instead of passing the whole user object.

Conclusion

In this article, we have extensively discussed the Passing of Data Between Screens in React Native. We discussed the types of params to be passed and a straightforward example to clear the concept.

We hope this blog has helped you enhance your knowledge regarding the Passing Data Between Screens. Do check out the awesome content on the Coding Ninjas Website, Android DevelopmentCoding Ninjas Studio ProblemsCoding Ninjas Studio Interview BundleCoding Ninjas Studio Interview ExperiencesCoding Ninjas CoursesCoding Ninjas Studio Contests, and Coding Ninjas Studio Test SeriesDo upvote our blog to help other ninjas grow. 

Happy Coding!

Live masterclass